如何用Python代码实现自动比较两个文件中的代码变化?,python代码,如何用Python代码实


如何用Python代码实现自动比较两个python文本与文件中的代码变化?用Python代码比较不同文件夹中代码变化实例讲解。在日常工作中我们常会修改其它人做的文件,修改过程中会出现多处不同,这不是人脑能记住的。在与原始文件做比对的时候,如果有脚本可以自动检测最好不过了。本文中就利用Python来做了这一实现,可以帮助对比检测两个不同文件夹中的代码做了如何变化。

以下为用Python代码比较不同文件夹中代码变化实例讲解代码部分:

python文件对比

需要python import导入python os模块。

import os;#导入os模块folderA = "F:\\Projects\\FreeImageV3_14_1\\".lower();folderB = u"E:\\Software\\图像解码库\\FreeImage3141\\FreeImage\\".lower();filePathsA = {};filePathsB = {};for root,dirs,files in os.walk(folderA):for fileName in files:filePathsA[(root + "\\" + fileName).lower()] = 1;for root,dirs,files in os.walk(folderB):for fileName in files:filePathsB[(root + "\\" + fileName).lower()] = 1;# 在filePathsA中查找到所有在filePathsB中不一致的文件的路径# 编橙之家 www.iplaypy.commodifiedFilePath = [];addedFilePath = [];for filePathA in filePathsA:folderALen = len(folderA);filePathB = folderB + filePathA[folderALen:]; idx = filePathA.rfind(".");if idx == -1:continue;        ext = filePathA[idx + 1:];ext = ext.lower();        if ext != "c" and ext != "h" and ext != "cpp" and ext != "cxx":continue;if filePathB not in filePathsB:addedFilePath.append(filePathA);continue;#以下打开操作后,一定要记得关闭text_file = open(filePathA, "r");textA = text_file.read();text_file.close();text_file = open(filePathB, "r");textB = text_file.read();text_file.close();if textA != textB:modifiedFilePath.append(filePathA);output = open('res.txt', 'w');output.write("added files:\n");for filePath in addedFilePath:output.write(filePath + "\n");output.write("modified files:\n");for filePath in modifiedFilePath:output.write(filePath + "\n");output.close();#关闭!

如何用Python代码实现自动比较两个文件中的代码变化?就简单介绍这些了。上面的python代码还可以更精简,供大家学习参考。也可以以这个代码为基础,做修改,做多文件比较,多类型比较等。

推荐阅读相关内容
Python open()函数文件打开、读、写write操作详解

编橙之家文章,

评论关闭