鱼C论坛

 找回密码
 立即注册
查看: 2534|回复: 1

[已解决]linux下对比2个文件内容的不同

[复制链接]
发表于 2018-3-19 17:08:05 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
我想要对比一下linux系统下的2个文件内容的不同,并且将不同的行统计次数,这个用python怎么实现?  麻烦给个思路,谢谢

例如:
file_a内容  123
file_b内容  123  4

就将这个4显示出来或者导入到文件,最后统计一下有多少行不同




谢谢
最佳答案
2018-3-19 17:13:53
参考python的第29课课后练习题
答案:
  1. def file_compare(file1, file2):
  2.     f1 = open(file1)
  3.     f2 = open(file2)
  4.     count = 0 # 统计行数
  5.     differ = [] # 统计不一样的数量

  6.     for line1 in f1:
  7.         line2 = f2.readline()
  8.         count += 1
  9.         if line1 != line2:
  10.             differ.append(count)

  11.     f1.close()
  12.     f2.close()
  13.     return differ

  14. file1 = input('请输入需要比较的头一个文件名:')
  15. file2 = input('请输入需要比较的另一个文件名:')

  16. differ = file_compare(file1, file2)

  17. if len(differ) == 0:
  18.     print('两个文件完全一样!')
  19. else:
  20.     print('两个文件共有【%d】处不同:' % len(differ))
  21.     for each in differ:
  22.         print('第 %d 行不一样' % each)
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2018-3-19 17:13:53 | 显示全部楼层    本楼为最佳答案   
参考python的第29课课后练习题
答案:
  1. def file_compare(file1, file2):
  2.     f1 = open(file1)
  3.     f2 = open(file2)
  4.     count = 0 # 统计行数
  5.     differ = [] # 统计不一样的数量

  6.     for line1 in f1:
  7.         line2 = f2.readline()
  8.         count += 1
  9.         if line1 != line2:
  10.             differ.append(count)

  11.     f1.close()
  12.     f2.close()
  13.     return differ

  14. file1 = input('请输入需要比较的头一个文件名:')
  15. file2 = input('请输入需要比较的另一个文件名:')

  16. differ = file_compare(file1, file2)

  17. if len(differ) == 0:
  18.     print('两个文件完全一样!')
  19. else:
  20.     print('两个文件共有【%d】处不同:' % len(differ))
  21.     for each in differ:
  22.         print('第 %d 行不一样' % each)
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-25 04:06

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表