比较两个目录和子目录以查找任何更改? [英] Comparing two directories with subdirectories to find any changes?

查看:54
本文介绍了比较两个目录和子目录以查找任何更改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于初学者来说,我现在只使用python大约2周,并且对它的过程还比较陌生,我正在尝试创建一个脚本,该脚本将两个目录与​​子目录进行比较,并打印出所有更改。我已经阅读了有关使用os.walk遍历目录的文章,并且设法编写了一种脚本,该脚本以一种易于理解的方式打印了目录及其子目录中的所有文件。我在这里也读过书,学习了如何比较两个目录,但是它只比较1个文件。

For starters I've only been playing with python for about a 2 weeks now and im relatively new to its proccessess, I'm trying to create a script that compares two directories with subdirectories and prints out ANY changes. I've read articles on hear about using os.walk to walk the directories and I've managed to write the script that prints all the files in a directory and its subdirectories in a understandable manner. I've also read on here and learned how to compare two directories but it only compares 1 file deep.

import os
x = 'D:\\xfiles'
y = 'D:\\yfiles'
q= [ filename for filename in x if filename not in y ]
print q 

很显然,这并不能满足我的要求。但是,这将列出所有文件和所有目录。

Obviously that does not do what I want it to. This however is listing all files and all directories.

import os
x = 'D:\\xfiles'
x1 = os.walk(x)
for dirName, subdirList, fileList in x1:
     print ('Directory: %s' % dirName)
     for fname in fileList:
     print ('\%s' % fname)

如何将它们组合并获得

推荐答案

编写一个函数以汇总您的列表。

Write a function to aggregate your listing.

import os

def listfiles(path):
    files = []
    for dirName, subdirList, fileList in os.walk(path):
        dir = dirName.replace(path, '')
        for fname in fileList:
            files.append(os.path.join(dir, fname))
    return files

x = listfiles('D:\\xfiles')
y = listfiles('D:\\yfiles')

您可以使用列表推导来提取不在两个目录中的文件。 / p>

You could use a list comprehension to extract the files that are not in both directories.

q = [filename for filename in x if filename not in y]

但使用更加高效和灵活。

But using sets is much more efficient and flexible.

files_only_in_x = set(x) - set(y) 
files_only_in_y = set(y) - set(x)
files_only_in_either = set(x) ^ set(y)
files_in_both = set(x) & set(y)
all_files = set(x) | set(y)

这篇关于比较两个目录和子目录以查找任何更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆