Skip to main content
 首页 » 编程设计

Python,在循环中识别文件给出错误 : setting an array element with a squence

2024年10月01日6thcjp

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

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

请您参考如下方法:

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