python文件比较 不同处的行号列号_如何在python中比较两个文件并打印不匹配的行号?...

您可以使用difflib模块。下面是一个使用其^{}类的简单示例:import difflib

import sys

with open('file1.txt') as file1, open('file2.txt') as file2:

line_formatter = '{:3d} {}'.format

file1_lines = [line_formatter(i, line) for i, line in enumerate(file1, 1)]

file2_lines = [line_formatter(i, line) for i, line in enumerate(file2, 1)]

results = difflib.Differ().compare(file1_lines, file2_lines)

sys.stdout.writelines(results)

输出:

^{pr2}$

第一列中的减号和加号字符表示以典型的diff实用程序样式替换的行。没有任何指示符意味着这两个文件中的行是相同的,如果愿意,可以禁止打印这些文件,但是为了保持示例简单,compare()方法创建的所有内容都将被打印。在

以下是两个文件并排显示的内容,行号如下:1 Attitude is a little thing that makes a big difference Attitude is a little thing that makes a big difference

2 The only disability in life is a bad attitude Everyone has his burden. What counts is how you carry it

3 Abundance is, in large part, an attitude Abundance is, in large part, an attitude

4 Smile when it hurts most A positive attitude may not solve all your problems

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值