0
votes

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:])

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

  1. Read all the .txt files
  2. Plot T% versus WL, plot ABS versus WL, save. (WL -> x variable)
  3. Continue for the next file, .. (two graphs for every .txt file)
  4. Then finish the loop, exit.

data looks like this

What I've tried

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

1 Answers

2
votes

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()

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.

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