循环遍历文件并绘图(Python) [英] Looping over files and plotting (Python)

查看:476
本文介绍了循环遍历文件并绘图(Python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据如图所示.我所有的数据都是.txt格式,我的目的是循环遍历文件并对其进行打印.第一行代表我的变量 (WL,ABS,T%),因此首先我需要先删除它们,然后再继续.

My data is look like as in the picture. All of my datas are in .txt format and my aim is to loop over files and plot them. First row represents my variables (WL, ABS, T%) so firstly I need to delete them before proceeding.

with open('Desktop/100-3.txt', 'r') as f:
data = f.read().splitlines(True)
with open('Desktop/100-3.txt', 'w') as f:
f.writelines(data[1:])

也许没有必要,但是我对Numpy还是很陌生.基本上,算法如下:

Probably it would not be necessary but I am very new in Numpy. Basically the algorithm will be as follows:

  1. 读取所有.txt文件
  2. 将T%与WL作图,将ABS与WL作图,保存. (WL-> x变量)
  3. 继续下一个文件..(每个.txt文件两个图表)
  4. 然后完成循环,退出.

数据看起来像这样

我尝试过的事情

from numpy import loadtxt
import os
dizin = os.listdir(os.getcwd())
for i in dizin:
  if i.endswith('.txt'):
   data = loadtxt("??",float)

推荐答案

对于这样的数据文件,我希望使用 glob 模块也很好地遍历了使用通配符作为过滤器的目录:

For data files like this I would prefer np.genfromtxt over np.loadtxt, it has many useful options you can look up in the docs. The glob module is also nice to iterate over directories with wildcards as filters:

from glob import glob
import numpy as np
import matplotlib.pyplot as plt

# loop over all files in the current directory ending with .txt
for fname in glob("./*.txt"):
    # read file, skip header (1 line) and unpack into 3 variables
    WL, ABS, T = np.genfromtxt(fname, skip_header=1, unpack=True)

    # first plot
    plt.plot(WL, T)
    plt.xlabel('WL')
    plt.ylabel('T%')
    plt.show()
    plt.clf()

    # second plot
    plt.plot(ABS, T)
    plt.xlabel('WL')
    plt.ylabel('ABS')
    plt.show()
    plt.clf()

下一步是对matplotlib进行一些研究,以使绘图看起来更好.

The next step would be to do some research on matplotlib to make the plots look better.

请让我知道该代码是否不起作用,然后我将尝试对其进行修复.

Please let me know if the code does not work, I'll try to fix it then.

添加了plt.clf()以在创建新图形之前清除图形.

Added plt.clf() to clear the figure before creating a new one.

这篇关于循环遍历文件并绘图(Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆