Python 根据名称移动文件

sda*_*891 2 python file move python-2.7

为了给予信任,我当前正在使用的代码来自cji的回复,此处。

我试图以递归方式从源文件夹中提取所有文件,并将它们从文件名前五个字符移动到文件夹中0:5

我的代码如下:

import os
import shutil

srcpath = "SOURCE"
srcfiles = os.listdir(srcpath)

destpath = "DESTINATION"

# extract the three letters from filenames and filter out duplicates
destdirs = list(set([filename[0:5] for filename in srcfiles]))


def create(dirname, destpath):
    full_path = os.path.join(destpath, dirname)
    os.mkdir(full_path)
    return full_path

def move(filename, dirpath):
    shutil.move(os.path.join(srcpath, filename)
                ,dirpath)

# create destination directories and store their names along with full paths
targets = [(folder, create(folder, destpath)) for folder in destdirs]

for dirname, full_path in targets:
    for filename in srcfiles:
        if dirname == filename[0:5]:
            move(filename, full_path)
Run Code Online (Sandbox Code Playgroud)

现在,更改srcfiles = os.listdir(srcpath)anddestdirs = list(set([filename[0:5] for filename in srcfiles])) 使用下面的代码可以获取一个变量中的路径和另一个变量中文件名的前五个字符。

srcfiles = []
destdirs = []

for root, subFolders, files in os.walk(srcpath):
    for file in files:
       srcfiles.append(os.path.join(root,file))
    for name in files:
       destdirs.append(list(set([name[0:5] for file in srcfiles])))
Run Code Online (Sandbox Code Playgroud)

我将如何修改原始代码来使用它......或者如果有人对我将如何去做这件事有更好的想法。谢谢。

tjo*_*son 5

我无法真正轻松地测试它,但我认为这段代码应该可以工作:

import os
import shutil

srcpath = "SOURCE"
destpath = "DESTINATION"

for root, subFolders, files in os.walk(srcpath):
    for file in files:
        subFolder = os.path.join(destpath, file[:5])
        if not os.path.isdir(subFolder):
            os.makedirs(subFolder)
        shutil.move(os.path.join(root, file), subFolder)
Run Code Online (Sandbox Code Playgroud)