0

我有一个包含数千个文件的目录。我想根据文件名将它们分类到目录中,但是许多文件名非常相似。

我的想法是我将不得不编写一堆正则表达式字符串,然后进行某种循环。这是我的问题:

这两个选项中的一个比另一个更优化吗?我是否遍历所有文件,并针对每个文件检查它与我的正则表达式,跟踪有多少匹配?还是我做相反的事情并遍历正则表达式并触摸每个文件?

我不得不用 python 来做,因为那是我最强大的语言,但我对其他想法持开放态度。

4

1 回答 1

0

这是我用于我的程序的一些代码,我已经为您的目的进行了修改,它获取一个目录(sort_dir)去那里的每个文件,并根据文件名创建目录,然后将文件移动到这些目录中。由于您没有提供任何关于您希望在何处或如何对文件进行排序的信息,因此您必须在我提到的地方添加该部分:

def sort_files(sort_dir):

    for f in os.listdir(sort_dir):
        if not os.path.isfile(os.path.join(sort_dir, f)):
            continue

        # this is the folder names to be created, what do you want them to be?       
        destinationPath = os.path.join(sort_dir,f) #right now its just the filename...

        if not os.path.exists(destinationPath):
            os.mkdir(destinationPath)

        if os.path.exists(os.path.join(destinationPath,f)):
            at = True
            while at:
                try:
                    shutil.move(os.path.join(sort_dir,f), \
                                os.path.join(destinationPath,f))
                    at = False
                except:
                    continue
        else:
            shutil.move(os.path.join(sort_dir,f), destinationPath)
于 2012-08-02T07:14:15.197 回答