Python对比俩个文件内容

大概总结了Python对比的方法

1、dfflib

复制代码
#!/usr/bin/python
import difflib
text1 = """text1:  #定义字符串1
This module provides classes and functions for comparing sequences.
including HTML and context and unified diffs."""
 
text1_lines = text1.splitlines() #以行进行分隔,以便进行对比
text2 = """text2: #定义第二个字符串
This module provides """
 
text2_lines = text2.splitlines()
d = difflib.Differ() #创建Differ对象
diff = d.compare(text1_lines, text2_lines)  #采用compare方法对字符串进行比较
print('\n'.join(list(diff)))
复制代码

 

2、set

复制代码
import difflib

a = open('./1.txt', 'U').readlines()
b = open('./2.txt', 'U').readlines()
diff = difflib.ndiff(a, b)
print(diff)
for i in diff:
    print(i)
    # if i.startswith('+'):
    #     print(i)

#or
print(set(b)-set(a))
复制代码

 

3、Python原始方法对比

复制代码
import sys
  
f1, f2=None,None
try:
    f1=open("pro1.txt", "r")
    m=f1.readlines()
except IOError:
    print "pro.txt does not exist!"
    sys.exit(2)
finally:
    if f1:
        f1.close()
# reead lines from mids2.txt
try:
    f2=open("pro.txt", "r")
    n=f2.readlines()
except IOError:
    print "pro1.txt does not exist!"
    sys.exit(2)
finally:
    if f2:
        f2.close()
#filter
for a in m:
    for b in n:
        if a==b:
            n.remove(b)    
 
for i in range(len(n)):
    n[i]=n[i].strip()
#print n
#print " ".join(n)
for aar in n:
    with open("baidu.txt","a") as fe:
        fe.write(aar+"\n")
复制代码

 

转自

(4条消息)使用python读取文件数据并转化为列表_longling0的博客-CSDN博客

https://blog.csdn.net/longling0/article/details/106172862

(3条消息)两行数据进行对比-python_程序员杂谈-CSDN博客

https://blog.csdn.net/trecn001/article/details/84586484

(3条消息)python对比两个文件的方法_yangchaoming的博客-CSDN博客

https://blog.csdn.net/qq_38072531/article/details/78205209

(4条消息)[376]python快速比较两个文件的不同_周小董-CSDN博客

https://blog.csdn.net/xc_zhou/article/details/81814361

python 比较2个文件内容 - 道以万计 - 博客园

https://www.cnblogs.com/snow-backup/p/11726931.html

Python:对比两段文本和两个文件不同的地方 - 简书

https://www.jianshu.com/p/cce80d678b48

posted @   paul_hch  阅读(3148)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
历史上的今天:
2018-09-10 Shell编程中while与for的区别及用法详解【转】
2018-09-10 rsync+inotify实现实时同步案例【转】
2018-09-10 Linux查看压缩文件内容【转】
2017-09-10 shell 监控磁盘使用率【转】
点击右上角即可分享
微信分享提示