Python, Identify file in loop giving error: setting an array element with a squence

54 views Asked by At

I am using the code I wrote below to make different plots from 500 txt files. One of the files has some of the y values missing in the form below

1.000    2.005
2.000    2.006
3.000 
4.000
5.000    2.009
6.000    2.010

This gives me the error message: setting an array element with a sequence

I understand why I am getting the error message and fortunately, I know which file is causing it. After spending ages trying to work this out myself, what I would like to know is how I could get Python to skip the file when it detects the error and enter the loop again on the next file, whilst printing “error detected on ‘filename’”

Thanks

Here is my code:

from pylab import plot, ylim, xlim, show, xlabel, ylabel, grid, xscale, clf, savefig
from numpy import loadtxt
import glob


for filename in glob.glob('file-???.txt'):
    data = loadtxt(filename)
    x = data[:,0]
    y = data[:,1]
    plot(x,y, 'r-o', linestyle='-', markersize=0.05)
    xlim()
    ylim()
    xlabel("Energy (eV).")
    ylabel("count")
    grid(True)
    show()
    print(filename)
    savefig(filename + '.png')
    clf()
1

There are 1 answers

0
Grisha On BEST ANSWER
from pylab import plot, ylim, xlim, show, xlabel, ylabel, grid, xscale, clf, savefig
from numpy import loadtxt
import glob


for filename in glob.glob('file-???.txt'):
    try:
      data = loadtxt(filename)
    except ValueError:
      continue
    x = data[:,0]
    y = data[:,1]
    plot(x,y, 'r-o', linestyle='-', markersize=0.05)
    xlim()
    ylim()
    xlabel("Energy (eV).")
    ylabel("count")
    grid(True)
    show()
    print(filename)
    savefig(filename + '.png')
    clf()