首页 > 解决方案 > 在 genfromtxt next(fhd) 中,添加新的“带打开文件”行时出现 StopIteration 错误

问题描述

我有一个需要分析的输入文件(它是一个包含 4 帧的轨迹文件),其中涉及每个帧的 for 循环并制作一个临时文件,然后进行计算。计算连同来自输入文件的一些信息将被写入输出文件。这是我的代码。“solvent”和“refpts”是包含数字的列表的名称。out 文件中需要这些列表的内容。

with open(infile, 'rb') as fi:
    with open(outfile,'a') as fj:
        fj.write('C, O, C-O distance, q, hbond')
        fj.write('\n')
        for frame in range(fr+1):
            fj.write(str(frame))
            fj.write('\n')
            chunk = list(islice(fi, nlines))
            #writes the snapshot's coordinate in a temporary file 'frame.gro'
            with open('frame.gro', 'w') as out:
                for line in chunk:
                    out.write(line)
            with open("frame.gro", 'r') as f:
                o = np.genfromtxt("frame.gro", dtype=None, skip_header=2, usecols=(0,1,3,4,5), max_rows=atoms) #this is line 182
                # obtain info, then do calcs ...
            for n in range(len(solvent)):
                for i in range(len(refpts)):
                    #calcs, add items to lists, etc
                    fj.write(str(refpts[i]))
            # ...rest of the code

一切正常,直到我添加了包含“fj”的每一行。发生此错误:

回溯(最后一次调用):文件“script.py”,第 182 行,在 o = np.genfromtxt("frame.gro", dtype=None, skip_header=2, usecols=(0,1,3,4, 5)、max_rows=atoms) 文件“/usr/local/lib/python2.7/dist-packages/numpy/lib/npyio.py”,第 1707 行,在 genfromtxt next(fhd) StopIteration

我能做什么?

编辑:更改标题中的一个词编辑#2:包含错误的实际行

标签: pythonnumpy

解决方案


扩展我的评论

        with open("frame.gro", 'r') as f:
            o = np.genfromtxt("frame.gro", dtype=None, skip_header=2, usecols=(0,1,3,4,5), max_rows=atoms) #this is line 182
            # obtain info, then do calcs ...

为什么你打开frame.gro,但不使用打开的文件?该genfromtxt行使用文件名,而不是f. 我不知道那个多余的开口是否会导致错误,但它确实暗示了一些草率的思考和/或测试。

如果我尝试应用genfromtxt到行数太少的文件 - 太少到skip. 错误行号不同,但这可能是因为我使用了不同的 Py3 numpy。

您需要检查新编写的内容frame.gro,并确保它在genfromtxt大小、内容等方面符合您的假设。


推荐阅读