python - 仅在Windows中的两个文件夹之间获取不匹配的文件名

时间:2013-06-17 08:55:33

标签: python python-2.7

我想在两个不同的文件夹之间找到不匹配的文件名。

例如,

,folder1包含:

file1.txt
file2.txt
file3.txt

folder2包含:

FILE1.txt
file2.txt
file3.TXT

结果应为:

FILE1.txt or file1.txt
file3.TXT or file3.txt

2 个答案:

答案 0 :(得分:1)

假设您在列表中有文件名,名为ab。然后你可以遍历两者并比较区分大小写的文件名,如果它们匹配,你打破循环,如果它们不匹配但是如果你将所有字符改为小写它们会匹配,你打印文件名,即< / p>

for file1 in a:
    for file2 in b:
        if file1==file2: break
        if file1.lower()==file2.lower():
            print '%s or %s' % (file1,file2)
            break

答案 1 :(得分:0)

fileNames1 = os.listdir('path1')
fileNames2 = os.listdir('path2')
fileNames1LC = { original.lower(): original for original in fileNames1 }
fileNames2LC = { original.lower(): original for original in fileNames2 }
for lc, original1 in fileNames1LC.iteritems():
    try:
        original2 = fileNames2LC[lc]
    except KeyError:
        # file in path1 found which has no partner in path2
        pass  # do whatever you want to do then
    else:  # found a partner in path2
        if original1 != original2:  # found different capitalisation
            print original2, "or", original1

通过输入pass语句,您可以处理path1中但path2中没有合作伙伴的文件。如果您需要处理path2中出现且path1中没有合作伙伴的文件,则还必须fileNames2LC行走。