我需要比较两个文件并将缺少的值写入另一个文件
Monday, sports, swimming
Tuesday, study, running
Wednesday, jog, sprint
Thursday, nothing, Play
Monday
Wednesday
Tuesday, study, running
Thursday, nothing, Play
import csv
f1 = file('C:\File1.csv', 'rb')
f2 = file('C:File2.csv', 'rb')
f3 = file('C:\output_file.csv', 'wb')
c1 = csv.reader(f1)
c2 = csv.reader(f2)
c3 = csv.writer(f3)
masterlist = [row for row in c2]
for hosts_row in c1:
for master_row in masterlist:
results_row = hosts_row
if hosts_row[0] == master_row[0]:
print results_row
c3.writerow(results_row)
Monday, sports, swimming
Wednesday, jog, sprint
答案 0 :(得分:0)
import csv
f1 = file('C:\File1.csv', 'rb')
f2 = file('C:File2.csv', 'rb')
f3 = file('C:\output_file.csv', 'wb')
c1 = csv.reader(f1)
c2 = csv.reader(f2)
c3 = csv.writer(f3)
masterlist = [row[0] for row in c2]
for hosts_row in c1:
if hosts_row[0] not in masterlist:
print hosts_row
c3.writerow(hosts_row)
答案 1 :(得分:0)
有点短而没有cvs
(你实际上并不需要它):
file1 = [line.strip() for line in open('File1.csv')]
file2 = [line.strip() for line in open('File2.csv')]
with open('output_File.cvs', 'w') as f:
for line in file1:
if not line.split(',')[0] in file2:
f.write(line + '\n')
编辑:您之间的单行爱好者可以用
替换循环f.writelines('\n'.join(filter(lambda l: not l.split(',')[0] in file2, file1)))