您的位置:首页 > 编程语言 > Python开发

Python使用difflib对比两个文件操作实例

2017-03-14 00:00 726 查看
#coding=utf8
'''
该库用来管理文件。
初始化函数调用读取配置文件模块中的Config类
用来获取下载路径、保存路径。
模块包含四个方法:
clearResultCSV(): 用来删除下载路径下所有的result开头的csv文件
moveCSVToSave():把下载路径下的result.csv文件重命名,并把重命名后的文件移动到保存路径下
getLastFileWithPath():获取保存路径下最新的文件,并带路径返回该文件
getLastFile():获得最新文件的命令并返回

'''
import os
#操作文件的包
import shutil
import re
import time
import difflib
#导入读取配置文件库的Config
from readConfig import Config

class FileManger(object):
def __init__(self,configObj=Config()):
try:
#创建一个Config对象实例
self.config=configObj
#通过对象实例调用方法getDownPath()
#获取下载路径
self.down=self.config.getDownPath()
#通过对象实例调用方法getSavePath()
#获取保存路径
try:
self.save=self.config.getSavePath()
if os.path.exists(self.save):
pass
else:
os.mkdir(self.save)
self.save=self.save
except Exception,e:
print "Save Report Error:",e
except Exception,e:
print e

def clearResultCSV(self):
try:
#获取下载路径下的所有文件
#并把文件保存在list变量fileList中
fileList=os.listdir(self.down)
#判断fileList是否为空,不为空执行if模块
if  fileList:
#对fileList中的元素进行循环
for item in fileList:
#查找下载路径下是否存在result开头的csv文件
#如果存在,则删除
if re.match("result(.*).csv",item):
#删除result开头的csv文件
os.remove(self.down+"\\"+item)
except Exception,e:
print e

def moveCSVToSave(self):
try:
#获取下载路径下的所有文件
#并把文件保存在list变量fileList中
fileList=os.listdir(self.down)
#获取当前时间并转换为字符串格式
now=time.strftime("%Y%m%d%H%M%S")
#判断fileList是否为空,不为空执行if模块
if  fileList:
#对fileList中的元素进行循环
for item in fileList:
try:
#查找下载路径下是否存在result.csv文件
#如果存在,对文件进行重命名
if re.match("result\.csv",item):
#获取带有路径的result.csv文件
oldfilename=self.down+"\\"+item
#重命名的命令格式是符:20170306143330.csv
newfileName=self.down+"\\"+now+".csv"
#对文件result.csv进行重命名为格式如:20170306143330.csv
os.rename(oldfilename,newfileName)
#把重命名的文件移动到保存路径下
shutil.move(newfileName, self.save)
except Exception,e:
print e
except Exception,e:
print e

def getLastReqement(self):
try:
#获取下载路径下的所有文件
#并把文件保存在list变量listfile中
listfile=os.listdir(self.save)
#判断listfile是否为空,不为空执行if模块
if len(listfile)>1:
#保存带有路径的最新文件
try:
self.diffPath=self.config.getDiffPath()
if os.path.exists(self.diffPath):
pass
else:
os.mkdir(self.diffPath)
self.diffPath=self.diffPath

lastfile=self.save+"\\"+listfile[-1]
#获取第二个比较新的文档
twofile=self.save+"\\"+listfile[-2]
lastestFile=open(lastfile,"r").readlines()
secondLastestFile=open(twofile,"r").readlines()
diffInf=difflib.ndiff(lastestFile,secondLastestFile)
diffHtml=open(self.diffPath+"\\"+"diff.log","w")
diffHtml.writelines(diffInf)
except Exception,e:
print "Save Diff Error:",e
except Exception,e:
print e

def test():
'''
创建一个测试脚本,执行冒烟测试。
用来验证程序功能能正常运行。
'''
#创建一个Config对象实例
fm=FileManger()
#fm.clearResultCSV()

fm.moveCSVToSave()
print fm.getLastFileWithPath(),os.listdir(fm.save)

if __name__=="__main__":
test()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: