Skip to main content
 首页 » 编程设计

Python:ValueError:混合迭代和读取方法会丢失数据

2025年02月15日9artech

当执行下面的脚本时,我得到:

ValueError:混合迭代和读取方法会丢失数据

我知道这是因为 num 在第一个 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)