python - 如何比较两个有变化的文件的 csv 文件和输出行?
问题描述
我对 python 很陌生,我正在尝试比较 2 个 csv 文件,它们的信息基本相同,但有些行被完全删除、新的或只更改了 1 个值。我需要一个输出文件,其中包含先前和当前 csv 文件的完整行,只有在发生更改时才在另一个顶部。我还需要在最前面添加一列,并根据它们来自哪个文件(以前或当前)标记这些行。
我曾尝试使用 difflib 中的 HtmlDiff,但这并没有以我想要的格式提供信息,并且它还显示了所有未更改的信息。我也试过 csv.reader 和 diff_rows 但那是一场灾难。
我最接近我的结果的是下面,但是在它输出的组合文件中,我无法知道哪一行来自哪个文件,因为它没有标签。尽量不要对我的代码笑得太厉害;我确信有更好的方法可以做到这一点,但我自己无法弄清楚,我非常感谢你的帮助。
如果我第二次没有定义以前的和当前的,那么删除输出为空。
previous = open('2019-08-21.csv', 'r', encoding="utf8")
current = open('2019-08-27.csv', 'r', encoding="utf8")
additions = set(current) - set(previous)
with open('Additions Aug 2019.csv', 'w', encoding="utf8") as file_out:
for line in additions:
file_out.write(line)
previous = open('2019-08-21.csv', 'r', encoding="utf8")
current = open('2019-08-27.csv', 'r', encoding="utf8")
removals = set(previous) - set(current)
with open('Removals Aug 2019.csv', 'w', encoding="utf8") as file_out:
for line in removals:
file_out.write(line)
filenames = ['Additions Aug 2019.csv', 'Removals Aug 2019.csv']
with open('Add, Rem Aug 2019.csv', 'w', encoding="utf8") as outfile:
for fname in filenames:
with open(fname) as infile:
for line in infile:
outfile.write(line)
previous.close()
current.close()
file_out.close()
解决方案
我设法用 pandas 找到了一个解决方案,并将分享给任何可能需要的人。
import pandas as pd
previous = open('2019-08-21.csv', 'r', encoding="utf8")
current = open('2019-08-27.csv', 'r', encoding="utf8")
df_p = pd.read_csv(previous)
df_p.drop(['Middle Name', 'Date of Birth', 'Place of Birth'], axis=1, inplace=True)
df_p.insert(0, 'Change Type', "Removed")
df_c = pd.read_csv(current)
df_c.drop(['Middle Name', 'Date of Birth', 'Place of Birth'], axis=1, inplace=True)
df_c.insert(0, 'Change Type', "Added")
df_f = df_c.append(df_p)
df_dedup = df_f.drop_duplicates(subset=['Full Name', 'Country', 'Position'], keep=False)
with open('Aug 2019 Changes.csv', 'w', encoding='utf8') as file_out:
df_dedup.to_csv(file_out, index=False)
推荐阅读
- ffmpeg - Python PyAudio 模仿 ffmpeg
- r - 如何计算分组表的总均值和标准差?
- php - 使用卷曲的问题 (56)
- python - Keras 输入形状和尺寸问题
- xamarin.forms - Xamarin ADAL AcquireTokenAsync 未从等待返回
- javascript - Firebase 函数设置自定义声明
- r - 如何访问 R 中 predict() 函数的值进行存储?
- json - 如何使用 Jekyll 插件缩小包含的 json 文件?
- xml - XMLStarlet,XPath - 如何根据节点删除属性
- ios - 如何在滚动视图的中心垂直对齐堆栈视图?