我有一个脚本,该脚本比较2个csv文件并将数据输出到新的CSV文件。我正在寻找帮助,以便能够以相同的代码将新输出文件中的数据附加到allhistory文件中。有人建议使用什么?
import csv
with open('allhistory.csv', 'r') as t1, open('filewithnewdata.csv', 'r') as t2:
fileone = t1.readlines()
filetwo = t2.readlines()
with open('update.csv', 'w') as outFile:
for line in filetwo:
if line not in fileone:
outFile.write(line)
您可以保留要写入update.csv
的行的列表,然后写入fileone
的内容,然后进行更新,从而覆盖现有文件。例如:
with open('allhistory.csv', 'r') as t1, open('filewithnewdata.csv', 'r') as t2:
fileone = t1.readlines()
filetwo = t2.readlines()
matches = []
with open('update.csv', 'w') as outFile:
for line in filetwo:
if line not in fileone:
matches.append(line)
outFile.write(line)
with open('allhistory.csv', 'w') as outFile:
outFile.write(''.join(fileone) + '\n' + ''.join(matches))
注意,您只是比较文件中的整行,您当前不使用csv
将每一行拆分为值。