[英]Python script to append data in one csv to another csv after compare
我有一个脚本,它比较 2 个 csv 文件并将数据输出到一个新的 CSV 文件。 我正在寻求帮助,以便能够将新 output 文件中的数据 append 转换为相同代码中的 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).strip() + '\n' + ''.join(matches))
请注意,您只是比较文件中的整行,您当前没有使用csv
将每行拆分为值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.