[英]how to compare difference in 2 txt files and output to a new txt file and print to shell using python
How to compare difference in 2 txt files and output and print it to shell?如何比较2个txt文件和输出的差异并将其打印到shell?
working files in this link此链接中的工作文件
https://wetransfer.com/downloads/a866da75bab9f884275e190e6b3740e220211023033329/647011 https://wetransfer.com/downloads/a866da75bab9f884275e190e6b3740e220211023033329/647011
Tried the code below doesn't output to a new file试过下面的代码没有输出到新文件
import pandas as pd
import os
def compare(File1,File2):
with open(r'D:..\..\..\members_1.txt') as f:
d=set(f.readlines())
with open(r'D:..\..\..\members_2.txt') as f:
e=set(f.readlines())
open('D:..\\..\\..\\output.txt','w').close() #Create the file
with open('D:..\\..\\..\\','a') as f:
for line in list(d-e):
f.write(line)
Expected output:预期输出:
of course use diff
当然使用
diff
Use drop_duplicates
with Pandas:对 Pandas 使用
drop_duplicates
:
df1 = pd.read_csv('members_1.txt', header=None).drop_duplicates()
df2 = pd.read_csv('members_2.txt', header=None).drop_duplicates()
out = pd.concat([df1, df2]).drop_duplicates(keep=False)
Output输出
>> print(*out[0].to_list(), sep='\n')
LEE RI KE
LIM YONG
KOH CHEE KIAT
LEE YONG
KOH CHEW KIAT
LEE RI KHEE
OR或者
Use set
in Python:在 Python 中使用
set
:
with open('members_1.txt') as fp1, open('members_2.txt') as fp2:
data1 = set([l.strip() for l in fp1])
data2 = set([l.strip() for l in fp2])
out = data1.symmetric_difference(data2)
Output:输出:
>>> print(*out, sep='\n')
KOH CHEW KIAT
LEE RI KE
LEE YONG
KOH CHEE KIAT
LEE RI KHEE
LIM YONG
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.