读取两个CSV文件

2024-07-02 09:58:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码:

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

问题是什么


Tags: csvnameinhellolinezipexefile
1条回答
网友
1楼 · 发布于 2024-07-02 09:58:26

正如@mkrieger1正确地说的,您已经耗尽了文件,无法再次读取。自动返回启动的一个好方法是使用for-else循环,其中else检查您是否达到eof。在那之后,你可以从头再来一次

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

相关问题 更多 >