【问题标题】:using CSV to process 2 text files line by line使用 CSV 逐行处理 2 个文本文件
【发布时间】:2013-05-07 19:24:40
【问题描述】:

我有两个文本文件。一个有大约 100 行 (A),另一个可能有大约 800 行 (B)。

我希望从 A 中读取一行,然后从 B 中读取所有行,然后打印一行,其中包含来自每个文件的值。

我正在使用 python 的 csv 模块,因为我知道这些文件格式和内容,并且它们都是逗号分隔的值。

我的代码看起来像这样...

import csv

infile1 = r'C:\zData\a.txt'
infile2 = r'C:\zData\b.txt'

csvfile1  = open(infile1, 'r')
myreader1 = csv.DictReader(csvfile1)

csvfile2  = open(infile2, 'r')
myreader2 = csv.DictReader(csvfile2)

for row1 in myreader1:

    for row2 in myreader2:

        print "GID = " + row1['GID'] + ", ABC = " + row2['ABC']

我怀疑这是一个简单的问题,但由于某种原因,这段代码只读取了外循环的第一行 (infile1) 和内循环的所有行 (infile2)。

我做错了什么?我尝试添加 myreader1.next,但这似乎没有任何影响。

谢谢。

【问题讨论】:

    标签: python loops csv


    【解决方案1】:

    您只能循环遍历csv.readercsv.DictReader 对象一次;那么文件指针在文件末尾。

    您可能应该只将第一个文件(较小的文件)中的所有行读入保存在内存中的列表中:

    with  open(infile1, 'r') as csvfile1:
        rows1 = list(csv.DictReader(csvfile1))
    

    现在您可以根据需要多次循环该列表:

    with open(infile2, 'r') as csvfile2:
        myreader2 = csv.DictReader(csvfile2)
    
        for row1 in myreader2:
            for row2 in rows1:
                print "GID = " + row1['GID'] + ", ABC = " + row2['ABC']
    

    另一种方法是每次在循环内重新打开myreader2

    with open(infile1, 'r') as csvfile1:
        myreader1 = csv.DictReader(csvfile1)
        for row1 in myreader1:
            with open(infile2, 'r') as csvfile2:
                myreader2 = csv.DictReader(csvfile2)
    
                for row2 in myreader2:
                    print "GID = " + row1['GID'] + ", ABC = " + row2['ABC']
    

    但是,如果您需要显示两个文件之间的匹配项,请将第一个文件读入字典:

    with  open(infile1, 'r') as csvfile1:
        rows1 = {row['GID']: row for row in csv.DictReader(csvfile1)}
    

    现在rows1 是一个字典,将GID 键映射到列出该值的行。这假定每一行都有一个唯一的GID 值。

    这将使将行与第二个 CSV 文件中的信息进行匹配变得容易:

    with open(infile2, 'r') as csvfile2:
        myreader2 = csv.DictReader(csvfile2)
    
        for row in myreader2:
            if row['GID'] in rows1:
                print 'Matching GID {}!'.format(row['GID'])
                print 'infile1: {}'.format(rows1[row['GID']])
                print 'infile2: {}'.format(row)
    

    【讨论】:

    • 可能值得一提的是另一种选择:将 file2 的 openDictReader 构造移动到循环内。这可能不是他真正想要的(正如您所建议的,将整个内容读入字典几乎可以肯定是最好的解决方案),但他可能很容易理解其中的区别。
    【解决方案2】:

    这个怎么样

    f = ["gid={}, abc={}".format(x['gid'],y['abc']) for y in myreader2 for x in myreader1]
    print f
    

    【讨论】:

      猜你喜欢
      • 2012-12-08
      • 1970-01-01
      • 1970-01-01
      • 2018-01-18
      • 2017-07-28
      • 2021-11-11
      • 2020-07-30
      • 1970-01-01
      相关资源
      最近更新 更多