Python for循环问题
对于循环问题:Python for循环问题,python,for-loop,Python,For Loop,对于循环问题: in1 = open('file_1', 'r') in2 = open('file_2', 'r') outf = open('out_file', 'w') for line in in1: s = line.split('\t') A = s[1][:-1] B = s[0] counter = 0 for line in in2: ss = line.split('\t') if A == ss[
in1 = open('file_1', 'r')
in2 = open('file_2', 'r')
outf = open('out_file', 'w')
for line in in1:
s = line.split('\t')
A = s[1][:-1]
B = s[0]
counter = 0
for line in in2:
ss = line.split('\t')
if A == ss[0] or A == ss[1]:
counter += 1
outf.write('%s\t%s\t%s\n'%(A,B,counter))
问题是它只通过in2中的行:in1中的第一行。我似乎不明白为什么。一个文件只能迭代一次。要从头开始,请使用
in2.seek(0)
在内部循环之前。第一次在2上循环时,你消耗它。可以重新打开它,也可以返回到开始处。一旦从内部循环中的文件2中读取了每一行,in2就位于文件的末尾。如果要为文件_1中的每一行读取文件_2,请添加:
in2.seek(0)
写入之前或之后。处理文件时,请执行此操作
with open('out_file', 'w') as outf:
with open('file_1', 'r') as in1:
for line in in1:
s = line.split('\t')
a = s[1][:-1]
b = s[0]
counter = 0
with open('file_2', 'r') as in2:
for line in in2:
etc.
与一起使用可确保文件已关闭
在最小的封闭范围内打开一个文件可以保证它可以一直被读取。重新打开文件的代价很高,但是有很多方法可以加快这个应用程序的速度
此外,请仅使用小写变量名。为类名保留大写。非常有意义。我删除了我的答案…出于某种原因,我认为可能存在范围问题。