Python:将文件移动到名称中包含模式的文件夹

时间:2018-10-17 10:05:59

标签: python organizer

要自动执行排序过程。但是无法解决。同一文件夹中约有数千个具有相同扩展名的文件。想要将它们排序到不同的文件夹,例如:XXpattern1XX.XXX文件到[pattern1]文件夹,Xpattern2XXX.XXX文件到[pattern2]文件夹,pattern3XXXX.XXX文件到[pattern3]文件夹,等等。

具有SO脚本,但找不到原始帖子。 但是还不知道如何更改它。

#!/usr/bin/env python3

import os
import subprocess
import shutil

# --------------------------------------------------------
reorg_dir = "/path/to/directory_to_reorganize"
exclude = (".jpg") # for example
remove_emptyfolders = True
# ---------------------------------------------------------

for root, dirs, files in os.walk(reorg_dir):
    for name in files:
        subject = root+"/"+name
        if name.startswith("."):
            extension = ".hidden_files"
        elif not "." in name:
            extension = ".without_extension"
        else:
            extension = name[name.rfind("."):]
        if not extension in exclude:
            new_dir = reorg_dir+"/"+extension[1:]
            if not os.path.exists(new_dir):
                os.mkdir(new_dir)
            n = 1; name_orig = name
            while os.path.exists(new_dir+"/"+name):
                name = "duplicate_"+str(n)+"_"+name_orig
                n = n+1
            newfile = new_dir+"/"+name
            shutil.move(subject, newfile)

def cleanup():
    filelist = []
    for root, dirs, files in os.walk(reorg_dir):
        for name in files:
            filelist.append(root+"/"+name)
    directories = [item[0] for item in os.walk(reorg_dir)]
    for dr in directories:
        matches = [item for item in filelist if dr in item]
        if len(matches) == 0:
            try:
                shutil.rmtree(dr)
            except FileNotFoundError:
                pass

if remove_emptyfolders == True:
    cleanup()

thnx

2 个答案:

答案 0 :(得分:1)

您可以尝试以下操作:

patterns = ['pattern1', 'pattern2', ...]
folders = [os.path.join(main_directory, pattern) for pattern in patterns]

# build folders
for folder in folders:
    if not os.path.exists(folder):
        os.makedirs(folder)

# move files in corresponding folders
for file in files:  # files is the list of all your file paths
    for pattern, folder in zip(patterns, folders):
        file_name = os.path.basename(file)
        if pattern in file_name:
            os.rename(file, os.path.join(folder, file_name))

答案 1 :(得分:-1)

检查hash中是否有带图案的路径