【问题标题】:Reading from two CSV files从两个 CSV 文件中读取
【发布时间】:2020-07-14 15:38:44
【问题描述】:

我的代码:

import csv

with open("firstfile.csv", encoding='utf-8-sig') as file1:
    one = csv.DictReader(file1)
    with open("secondfile.csv", "r") as file2:
        for line in one:
            print(line)
            for line2 in file2:
                s = line["Owner"]
                if s in line2:
                    print(True)
                    break
            print(s)

当我运行这段代码时,我得到了

{'File Name': 'hofie.exe', 'Owner': 'hello'}
hello
{'File Name': 'feiofejp.zip', 'Owner': 'yo'}
hello
{'File Name': 'fewfew1.exe', 'Owner': 'foooffoo'}
hello

当我期待时:

{'File Name': 'hofie.exe', 'Owner': 'hello'}
hello
{'File Name': 'feiofejp.zip', 'Owner': 'yo'}
yo
{'File Name': 'fewfew1.exe', 'Owner': 'foooffoo'}
foooffoo

firstfile.csv:

File Name,Owner
hofie.exe,hello
feiofejp.zip,yo
fewfew1.exe,foooffoo

secondfile.csv:

ihfoiehofiejwifpewhf

有什么问题?

【问题讨论】:

标签: python csv iterator


【解决方案1】:

正如@mkrieger1 正确所说,您已用尽文件,无法再次阅读。一种自动返回开始的漂亮而简洁的方法是使用 for else 循环,else 检查是否达到了 eof。之后你可以再次开始file.seek(0)

import csv

with open("firstfile.csv", encoding='utf-8-sig') as file1:
    one = csv.DictReader(file1)
    with open("secondfile.csv", "r") as file2:
        for line in one:
            print(line)
            for line2 in file2:
                s = line["Owner"]
                if s in line2:
                    print(True)
                    break
            else:
                file2.seek(0)
            print(s)

打印

OrderedDict([('File Name', 'hofie.exe'), ('Owner', 'hello')])
hello
OrderedDict([('File Name', 'feiofejp.zip'), ('Owner', 'yo')])
yo
OrderedDict([('File Name', 'fewfew1.exe'), ('Owner', 'foooffoo')])
foooffoo

【讨论】:

    猜你喜欢
    • 2020-06-30
    • 2020-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-09
    相关资源
    最近更新 更多