Python根据名称移动文件

时间:2016-03-18 17:38:08

标签: python python-2.7 file move

为了表示赞赏,我目前使用的代码来自 cji here.

的回复

我试图以递归方式从源文件夹中提取所有文件,然后将它们从文件名前移到文件夹中的前五个字符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)

现在,使用下面的代码更改srcfiles = os.listdir(srcpath)destdirs = 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])))

我将如何修改原始代码以使用此...或者如果有人对如何执行此操作有更好的了解。感谢。

1 个答案:

答案 0 :(得分:0)

我无法轻易地对其进行测试,但我认为此代码应该有效:

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)