【问题标题】:in genfromtxt next(fhd), StopIteration error upon adding a new "with open file" line在 genfromtxt next(fhd) 中,添加新的“带打开文件”行时出现 StopIteration 错误
【发布时间】:2018-10-27 20:20:54
【问题描述】:

我有一个需要分析的输入文件(它是一个包含 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”的每一行之前,一切正常。发生此错误:

Traceback(最近一次调用最后一次): 文件“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 下一个(高清) 停止迭代

我能做什么?

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

【问题讨论】:

  • 你为什么open'frame.gro',然后在genfromtxt中使用相同的文件名。如果您将文件名提供给genfromtxt,它将打开它以供自己阅读。要么将f 传递给genfromtxt,要么不要将gen 嵌入到with 块中。
  • 如果清理这些文件 open 不能解决这个问题,我会检查 frame.gro 文件的大小。它真的有 2 个标题行吗?多少数据线。 atoms 是什么?
  • @hpaulj 我需要先写然后读。
  • 我不是在问写作。我询问有关冗余读取打开的问题。

标签: python numpy


【解决方案1】:

扩展我的评论

        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 太少),我会收到 StopIteration 错误。错误行号不同,但这可能是因为我使用的是不同的 Py3 numpy。

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

【讨论】:

    猜你喜欢
    • 2021-07-23
    • 2022-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多