简体   繁体   中英

Reading from two CSV files

My code:

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)

When I run this code I get

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

when I am expecting:

{'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

What is the issue?

As @mkrieger1 correctly said you have exhausted the file and you can't read it again. A nice and sleek way to auto return to start is by using a for else loop, where else checks if you reached eof. After that you can file.seek(0) at the begining again.

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)

prints :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM