从目录

时间:2017-02-01 20:09:29

标签: python shutil os.walk

我正在尝试从文件夹中的子目录移动pdf文件。此代码可以运行并移动所有找到的pdf。我想只使用以下代码从文本文件中移动与数字匹配的pdf文件:

with open('LIST.txt', 'r') as f:
    myNames = [line.strip() for line in f]
    print myNames

完整代码:

import os
import shutil

with open('LIST.txt', 'r') as f:
    myNames = [line.strip() for line in f]
    print myNames

dir_src = r"C:\Users\user\Desktop\oldfolder"
dir_dst = r"C:\Users\user\Desktop\newfolder"

for dirpath, dirs, files in os.walk(dir_src):
    for file in files:
        if file.endswith(".pdf"):
            shutil.copy( os.path.join(dirpath, file), dir_dst )

文本文件内容示例:

111111
111112
111113
111114

1 个答案:

答案 0 :(得分:0)

首先,在此处创建set而不是列表,以便查找更快:

myNames = {line.strip() for line in f}

然后对于过滤器,我假设myNames必须与文件的基名(减去扩展名)匹配。所以而不是:

    if file.endswith(".pdf"):
        shutil.copy( os.path.join(dirpath, file), dir_dst )

检查扩展名,以及basename减去扩展名是否属于您之前创建的集合:

    bn,ext = os.path.splitext(file)
    if ext == ".pdf" and bn in myNames:
        shutil.copy( os.path.join(dirpath, file), dir_dst )

要使文件名与myNames中的子字符串匹配,您不能依赖in方法。你可以这样做:

    if ext == ".pdf" and any(s in file for s in myNames):
相关问题