大家好,并提前致谢。
我正在尝试从两个不同的csv文件中提取不匹配的列字符串,并将结果写入新的cvs文件中。
到目前为止,我已经写了这段代码:
import csv
with open(r'C:\Users\DataAnalyst\Desktop\phonesdata\sms_03.csv', 'r') as sms:
sms_indices = dict((r[1], i) for i, r in enumerate(csv.reader(sms)))
with open(r'C:\Users\DataAnalyst\Desktop\phonesdata\marketing.csv', 'r') as marketing:
reader = csv.reader(marketing)
f3 = open('results.csv', 'w')
c3 = csv.writer(f3)
sms_mark = list(marketing)
for sms_03_row in sms:
row = 1
found = False
results_row = sms_03_row #Moved out from nested loop
for marketing_row in sms_mark:
x = marketing[0]
if sms_03_row[1] != marketing_row[0]:
results_row.append(x)
found = True
break
row += 1
if not found:
results_row.append('Not found')
c3.writerow(results_row)
sms.close()
marketing.close()
f3.close()
然而,我得到了这个:
Traceback (most recent call last):
File "<ipython-input-5-bc26b28cdf70>", line 1, in <module>
sms_mark = list(marketing)
ValueError: I/O operation on closed file.
我该如何解决?有了这段代码,我会得到不匹配的字符串吗?
谢谢!
答案 0 :(得分:0)
你有一些indentadion问题。无论如何让with
语句关注打开和关闭文件,你会没事的:
import csv
with open(r'<path_to_sms>', 'r') as sms, open(r'<path_to_marketing>') as marketing,
open(r'results.csv', 'w') as f3:
sms_indices = dict((r[1], i) for i, r in enumerate(csv.reader(sms)))
reader = csv.reader(marketing)
c3 = csv.writer(f3)
sms_mark = list(marketing)
results_row = []
# your stuff goes here
c3.writerow(results_row)