【问题标题】:for loop problem [duplicate]for循环问题[重复]
【发布时间】:2011-05-04 15:47:11
【问题描述】:

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。我似乎无法弄清楚为什么。

【问题讨论】:

    标签: python for-loop


    【解决方案1】:

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

    in2.seek(0)
    

    在内循环之前。

    【讨论】:

    • 非常有意义。我删除了我的答案......出于某种原因认为可能存在范围问题。
    【解决方案2】:

    第一次循环in2 时,您会使用它。要么重新打开它,要么回到起点。

    【讨论】:

      【解决方案3】:

      一旦您在内部循环中读取了 file_2 中的每一行,那么 in2 就位于文件末尾。如果要读取 file_1 中每一行的 file_2,请添加:

          in2.seek(0)
      

      就在写作之前或之后。

      【讨论】:

        【解决方案4】:

        处理文件时,请这样做

        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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-08-09
          • 1970-01-01
          • 1970-01-01
          • 2021-10-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-10-10
          相关资源
          最近更新 更多