python实现比较文件内容异同

yipeiwu_com6年前Python基础

本文实例为大家分享了python实现比较文件内容异同的具体代码,供大家参考,具体内容如下

import sys
import difflib
import time
import os
"""
创作时间:2017-10-08 23:30 09
版本: 1.0.0
"""
def main():
  """主函数"""
  try:
    f1 = sys.argv[1]#获取文件名
    f2 = sys.argv[2]
  except Exception as e:
    print("Error: "+ str(e))
    print("Usage : python compareFile.py filename1 filename2")
    sys.exit()

  if f1 == "" or f2 == "":#参数不够
    print("Usage : python compareFile.py filename1 filename2")
    sys.exit()

  tf1 = readFile(f1)
  tf2 = readFile(f2)

  d = difflib.HtmlDiff()#创建一个实例difflib.HtmlDiff
  writeFile(d.make_file(tf1,tf2))#生成一个比较后的报告文件,格式为html

def readFile(filename):
  """读取文件,并处理"""
  try:
    fileHandle = open(filename, "r")
    text = fileHandle.read().splitlines()
    fileHandle.close()
    return text
  except IOError as e:
    print("Read file error: "+ str(e))
    sys.exit()

def writeFile(file):
  """写入文件"""
  diffFile = open('diff_{}_.html'.format(time.strftime("%Y_%m_%d_%H_%M_%S",time.localtime())), "w")
  diffFile.write("<meta charset='UTF-8'>")
  diffFile.write(file)
  print("The file on {}".format(os.path.abspath(str(diffFile.name))))#提示文件生成在什么地方
  diffFile.close()


if __name__ == "__main__":
  main()

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

用python + hadoop streaming 分布式编程(一) -- 原理介绍,样例程序与本地调试

用python + hadoop streaming 分布式编程(一) -- 原理介绍,样例程序与本地调试

MapReduce与HDFS简介 什么是Hadoop? Google为自己的业务需要提出了编程模型MapReduce和分布式文件系统Google File System,并发布了相关论文...

Django中在xadmin中集成DjangoUeditor过程详解

Django中在xadmin中集成DjangoUeditor过程详解

环境 python版本:3.6 django:1.10.8 1.下载xadmin https://github.com/sshwsfc/xadmin 下载DjangoUeditor ht...

Python编码类型转换方法详解

本文实例讲述了Python编码类型转换方法。分享给大家供大家参考,具体如下: 1:Python和unicode 为了正确处理多语言文本,Python在2.0版后引入了Unicode字符串...

django 自定义过滤器的实现

自定义模版过滤器 虽然DTL给我们内置了许多好用的过滤器。但是有些时候还是不能满足我们的需求。因此Django给我们提供了一个接口,可以让我们自定义过滤器,实现自己的需求。 模版过滤...

python存储16bit和32bit图像的实例

笔记:python中存储16bit和32bit图像的方法。 说明:主要是利用scipy库和pillow库,比较其中的不同。 ''' 测试16bit和32bit图像的python存储方...