简体   繁体   English

如何比较2个txt文件的差异并输出到新的txt文件并使用python打印到shell

[英]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:预期输出:

txt 文件中的预期输出

of course use diff当然使用diff

difflib.Differ difflib.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.

相关问题 Python,比较2个txt文件,找到第2个txt文件中唯一的行和output到一个新的txt文件 - Python, compare 2 txt files, find unique lines in the 2nd txt file and output to a new txt file 比较两个txt文件并在txt文件中逐行打印差异 - Compare two txt files and print the difference line by line in txt file 使用Python将输出打印到文本文件(.txt) - Print output to text file (.txt) using Python Python:如何将打印输出重定向到 txt 文件? - Python: How to redirect print output to txt file? 如何在Python中比较2个txt文件 - How to compare 2 txt files in Python 在Windows中使用子过程将输出Shell输出到txt文件 - Shell output to a txt file using subprocess in Windows 如何使用 Python 代码以表格格式打印多个 txt 文件的 output? - How to print output of multiple txt file in tabular format with Python code? 在Python中将打印输出重定向到.txt文件 - Redirecting the print output to a .txt file in Python python中如何在多个文本文件中显示输出,例如:在1.txt,2.txt,3.txt中打印1到10的数字 - How to show the output in multiple text files in python, for example: print digits from 1 to 10 in 1.txt,2.txt,3.txt 输入数据文件.txt并使用Python将特定数据输出到新的.txt文件 - Input a data file .txt and output specific data to a new .txt file using Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM