2011-05-04 138 views
0

对于循环问题:for循环问题

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)) 

的问题是,它只能通过for line in in2:去为第一line in in1。我似乎无法弄清楚为什么。

回答

6

您只能迭代一次文件。要再次从头开始,请使用

in2.seek(0) 

之前的内部循环。

+0

非常有意义。我删除了我的答案......出于某种原因,认为可能存在范围问题。 – 2011-05-04 15:52:33

2

第一次循环使用in2时,就会消耗它。重新打开它,或者回到开头。

0

一旦你从内部循环中的file_2中读取了每一行,那么in2就在文件结尾。如果你想读file_2在file_1每一行则附加:

in2.seek(0) 

之前或写操作后。

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. 

使用with保证您的文件被关闭。

在最小的封闭范围内打开一个文件保证了它可以一直读取。保持重新打开文件的代价很高,但有很多方法可以加快此应用程序的速度。

此外,请仅使用lowercase变量名称。为类名保留Uppercase