Python: ValueError: Mixing iteration and read methods would lose data

这一生的挚爱 提交于 2019-12-24 02:15:24

问题


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) 

回答1:


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) 


来源:https://stackoverflow.com/questions/42423210/python-valueerror-mixing-iteration-and-read-methods-would-lose-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!