【问题标题】:Copy files from text file in directory从目录中的文本文件复制文件
【发布时间】:2017-02-01 20:09:28
【问题描述】:

我正在尝试从文件夹的子目录中移动 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

【问题讨论】:

  • 您只想从文本文件中移动匹配的文件(以什么方式?文件名?内容?)(我假设您的意思是您的'LIST.txt'?)

标签: python shutil os.walk


【解决方案1】:

首先,在这里创建一个set 而不是列表,这样查找会更快:

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

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

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

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

    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):

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-23
    • 2020-10-17
    • 1970-01-01
    • 2010-11-26
    • 2013-10-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多