[英]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:第一个文件.csv:
File Name,Owner
hofie.exe,hello
feiofejp.zip,yo
fewfew1.exe,foooffoo
secondfile.csv:第二文件.csv:
ihfoiehofiejwifpewhf
What is the issue?问题是什么?
As @mkrieger1 correctly said you have exhausted the file and you can't read it again.正如@mkrieger1 正确所说,您已经用尽了文件,并且无法再次阅读。 A nice and sleek way to auto return to start is by using a for else loop, where else checks if you reached eof.
一种自动返回开始的漂亮而简洁的方法是使用 for else 循环,其中 else 检查您是否达到了 eof。 After that you can
file.seek(0)
at the begining again.之后,您可以再次从头开始
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)
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.