![](/img/trans.png)
[英]Reading two files, a csv and xls, and bring columns from csv to xls based on subnet(csv)/ip(xls) match
[英]Reading from two CSV files
我的代码:
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
第一个文件.csv:
File Name,Owner
hofie.exe,hello
feiofejp.zip,yo
fewfew1.exe,foooffoo
第二文件.csv:
ihfoiehofiejwifpewhf
问题是什么?
正如@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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.