Python:ValueError:混合迭代和读取方法会丢失数据 [英] Python: ValueError: Mixing iteration and read methods would lose data
本文介绍了Python:ValueError:混合迭代和读取方法会丢失数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
执行下面的脚本时,我得到:
ValueError:混合迭代和读取方法会丢失数据
我了解这是因为num位于first for循环内,而last_host是num的依赖项,但我不知道如何解决此问题.
#!/usr/bin/env python2
import datetime as dt
import glob as glob
import os as os
import shutil as shutil
import signal as signal
import subprocess as sp
import sys as sys
# Open PDB file and read coordinates
pdb_file = open('align_z.pdb', 'r')
new_pdb_file = open('vac.pdb', 'w')
#Get last host atom
for num, line in enumerate(pdb_file, 1):
if "L01" in line:
print num
break
last_host=int(num)
print(last_host-1)
for atom in range(0, last_host-1):
data = pdb_file.readline()
new_pdb_file.write(data)
解决方案
一旦通过enumerate
迭代pdf_file
,就无法再次对其进行迭代,除非调用pdb_file.seek(0)
seek(0)将流位置更改为开头>
这是我的修改内容
num = 1
for line in pdb_file:
num += 1
if "L01" in line:
print num
break
pdb_file.seek(0) # go back to the beginning and then it can be iterated again
last_host=int(num)
print(last_host-1)
for atom in range(0, last_host-1):
data = pdb_file.readline()
new_pdb_file.write(data)
When executing the script below I get:
ValueError: Mixing iteration and read methods would lose data
I understand that this is because num is inside the first for loop and last_host is dependend of num but I have no idea how to work around this.
#!/usr/bin/env python2
import datetime as dt
import glob as glob
import os as os
import shutil as shutil
import signal as signal
import subprocess as sp
import sys as sys
# Open PDB file and read coordinates
pdb_file = open('align_z.pdb', 'r')
new_pdb_file = open('vac.pdb', 'w')
#Get last host atom
for num, line in enumerate(pdb_file, 1):
if "L01" in line:
print num
break
last_host=int(num)
print(last_host-1)
for atom in range(0, last_host-1):
data = pdb_file.readline()
new_pdb_file.write(data)
解决方案
Once you iterate pdf_file
by enumerate
you cannot iterate it again except invoking pdb_file.seek(0)
seek(0) changes the stream position to the beginning
Here's my modification:
num = 1
for line in pdb_file:
num += 1
if "L01" in line:
print num
break
pdb_file.seek(0) # go back to the beginning and then it can be iterated again
last_host=int(num)
print(last_host-1)
for atom in range(0, last_host-1):
data = pdb_file.readline()
new_pdb_file.write(data)
这篇关于Python:ValueError:混合迭代和读取方法会丢失数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文