ValueError 问题以及如何从两个文件中提取不匹配的字符串?
ValueError issue and how to extract not matching strings from two files?
大家好,提前致谢。
我正在尝试从两个不同的 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.
我该如何解决?有了这段代码,我会得到不匹配的字符串吗?
谢谢!
你有一些缩进问题。无论如何,让 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)
大家好,提前致谢。
我正在尝试从两个不同的 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.
我该如何解决?有了这段代码,我会得到不匹配的字符串吗?
谢谢!
你有一些缩进问题。无论如何,让 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)