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

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

我正在使用我在下面编写的代码从 500 个 txt 文件中制作不同的图。其中一个文件在下面的表格中缺少一些 y 值

1.000 2.005
2.000 2.006
3.000
4.000
5.000 2.009
6.000 2.010

这给了我错误信息:用序列设置数组元素

我明白为什么会收到错误消息,幸运的是,我知道是哪个文件导致的。在花了很长时间尝试自己解决这个问题之后,我想知道的是如何让 Python 在检测到错误时跳过文件并在下一个文件上再次进入循环,同时打印“检测到错误”关于“文件名””

谢谢

这是我的代码:

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