使用 glob 查找其中具有相同编号的重复文件名

Using glob to find duplicate filenames with the same number in it

我目前正在编写一个脚本,循环遍历文件夹中的所有文件并根据命名约定重命名它们。

我想实现的是以下;如果脚本找到 2 个文件名中具有相同编号的文件(例如“101 test”和“101 real”),它将把这两个文件移动到名为 'duplicates'.

的不同文件夹中

我原来的计划是使用glob循环遍历文件夹中的所有文件,并将每个包含特定编号的文件添加到列表中。然后将检查列表的长度,如果长度超过 1(即有 2 个文件具有相同的编号),则文件将位于此 'duplicates' 文件夹中。但是由于某种原因,这不起作用。

这是我的代码,我希望比我更有经验的人能告诉我如何实现我的目标,谢谢!:

app = askdirectory(parent=root)




for x in range(804):
    listofnames = []
    real = os.path.join(app, '*{}*').format(x)
    for name in glob.glob(real):
        listofnames.append(name)
        y = len(listofnames)
        if y > 1:
            for names in listofnames:
                path = os.path.join(app, names)
                shutil.move(path,app + "/Duplicates")

一个简单的方法是在这样的结构中收集带有数字的文件名:

numbers = {
     101: ['101 test', '101 real'],
     93: ['hugo, 93']
}

如果这个字典中的列表比一个列表长,则移动。

import re, os
from collections import defaultdict

app = askdirectory(parent=root)
# a magic dict
numbers = defaultdict(list)

# list all files in this dir
for filename in os.listdir(app):
    # \d+ means a decimal number of any length
    match = re.search('\d+', filename)

    if match is None:
        # no digits found
        continue

    #extract the number
    number = int(match.group())

    # defaultdict magic
    numbers[number].append(filename)

for number, filenames in numbers.items():
    if len(filenames) < 2:
        # not a dupe
        continue
    for filename in filenames:
        shutil.move(os.path.join(app, filename),
                    os.path.join(app, "Duplicates"))

defaultdict magic 只是以下代码的简写:

    if number not in numbers:
        numbers.append(list())
    numbers[number] = filename