如何比较两个目录并在python中输出更改的文件
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何比较两个目录并在python中输出更改的文件相关的知识,希望对你有一定的参考价值。
我在Linux中有两个目录,其中有两个文件。我需要比较这两个目录并打印出更改的文件。
folder1:
file1.txt file2.txt
folder2:
file1.txt file2.txt
我需要将folder1
与folder2
进行比较,并打印出这两个目录中不同的文件名。我想首先使用ls
命令获取文件列表并将它们放在list
中,然后使用python的filecmp
进行比较,如下所示:
import os
import filecmp
folder1_path = "/home/user/folder1/"
folder2_path = "/home/user/folder2/"
def ls(path):
all = []
walked = os.walk(path)
for base, sub_f, files in walked:
for sub in sub_f:
entry = os.path.join(base,sub)
entry = entry[len(path):].strip("\\")
all.append(entry)
for file in files:
entry = os.path.join(base,file)
entry = entry[len(path):].strip("\\")
all.append(entry)
all.sort()
return all
def folder_diff(folder1_path, folder2_path):
folder1_list = ls(folder1_path)
folder2_list = ls(folder2_path)
for item1, item2 in zip(folder1_list, folder2_list):
res = filecmp.cmp(folder1_path + item1, folder2_path + item2)
data = folder_diff(folder1_path, folder2_path)
print(data)
当文件存在于两个文件夹中时,这会引发错误FileNotFound
。任何人都可以建议任何更新。谢谢
答案
为了只有一个功能你可以使用它:
def folder_diff():
folder1 = os.listdir(PATH1) # folder containing your files
folder2 = os.listdir(PATH2) # the other folder
for item1 in folder1:
for item2 in folder2:
if(item1==item2):
res = filecmp.cmp(PATH1+item1, PATH2+item2)
if __name__ == "__main__":
import os
import filecmp
PATH1 = ''
PATH2 = ''
data = folder_diff()
print(data)
另一答案
您也可以使用glob
模块完成此操作
import os
import glob
import filecmp
comparison = []
for each in glob.glob('home/user/folder1/**'):
for each1 in glob.glob('home/user/folder2/**'):
if os.path.basename(each) == os.path.basename(each1):
comparison.append(filecmp.cmp(each, each1))
print(comparison)
以上是关于如何比较两个目录并在python中输出更改的文件的主要内容,如果未能解决你的问题,请参考以下文章