python - 在 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:包含错误的实际行
解决方案
扩展我的评论
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
大小、内容等方面符合您的假设。
推荐阅读
- json - 如何将 JSON(尤其是 NBA 统计数据)导入 Google 表格
- javascript - 如何将变量作为索引键传递给状态
- database - BIGINT 列的最有效索引仅通过正/负号过滤/查询?
- typescript - VSCode 在编译时显示 .vue 导入的“找不到模块”TS 错误
- ruby-on-rails - extension_whitelist 阻止 Faker::Avatar.image
- powershell - PowerShell New-ScheduledTaskAction 使用引号
- python - 在django中更新forgeign key模型的数据
- c# - C#将对象转换为字符串数组的最佳方法
- webview - AeroGear SSO 登录使用 Keycloak 后端嵌入式 Safari 浏览器而不是外部 Safari 浏览器
- c++ - 为什么 c++ 中的引用传递用 functionName(dataType& variableName) 表示?