![](/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.