首页 > 解决方案 > 如何使用 python 将某些文件从多个子目录复制到一个目标?

问题描述

我是 python 新手,我正在尝试编写一个脚本,将 .txt 文件从不同的子目录移动到一个新文件夹。

import os
import shutil

source_directory = os.path.join('mysourcedirectory', 'source')
target_directory = os.path.join('destinationdirectory', 'target')

operation= 'copy'

for src_dir, dirs, files in os.walk(source_directory):
    if file.endswith(".txt"):
        shutil.copy(os.path.join(target_directory, file))
        

有人能告诉我哪里出了问题以及如何修改它吗?我还希望能够修改这些文件(删除标题,将文件重命名为连续数字)。这仍然可以在一个脚本中完成吗?

标签: pythonfileloopscopy

解决方案


推荐阅读