python - 将文件从一个文件夹复制到另一个文件夹,并在 .txt 文件中使用匹配的名称

标签 python r shell

我想根据 .txt 文件中的匹配文件名将文件从一个大文件夹复制到另一个文件夹。

我的 list.txt 文件包含文件名:

S001
S002
S003

另一个大文件夹包含许多前文件。 S001、S002、S003、S004、S005

我只想从这个大文件夹中复制与我的 list.txt 文件中的文件名相匹配的文件。

我尝试过 Bash、Python - 不起作用。

for /f %%f in list.txt do robocopy SourceFolder/ DestinationFolder/ %%f

也不起作用。

我的 Python 逻辑不起作用:

import os
import shutil

def main():

    destination = "DestinationFolder/copy"

    source = "SourceFolder/MyBigData"

    with open(source, "r") as lines:
        filenames_to_copy = set(line.rstrip() for line in lines)

    for filenames in os.walk(destination):
        for filename in filenames:
            if filename in filenames_to_copy:
                shutil.copy(source, destination)

有 Bash、Python 或 R 的答案吗?

谢谢

最佳答案

我认为你的Python代码的问题是,使用os.walk()你的filename每次都会是一个列表,在你的filenames_to_copy中找不到它。

我建议尝试使用 os.listdir() ,因为这将以字符串形式返回文件名/文件夹名称列表 - 更容易与您的 filenames_to_copy 进行比较。

其他注意事项 - 也许您想在源而不是目标上执行 os.listdir() (或 os.walk())。目前,只有当文件已存在于目标中时,您才将文件从源复制到目标。

关于python - 将文件从一个文件夹复制到另一个文件夹,并在 .txt 文件中使用匹配的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57202159/

相关文章:

python - 使用 PIL 在 python 中调整图像大小

r - 如何检查一个单词是否是回文?

r - R 函数中无声与冗长的约定

r - 当 url 在 YAML 元数据中时,如何强制 pandoc 不构建 <a> 标签

python - 如何将 python 模块与 shell 命令结合使用

python - 在python中,将用户更改为SU后如何执行hadoop命令?

linux - 从 shellcode 启动的 Shell 在启动时立即停止

python - 两个日期时间之间的django分钟

python - 在 Python 类中初始化和使用常量的最佳方法是什么?

python导入模块比较麻烦