【问题标题】:Move files from multiple directories to single directory将文件从多个目录移动到单个目录
【发布时间】:2015-05-18 05:57:25
【问题描述】:

我正在尝试使用os.walk() 模块遍历多个目录并将每个目录的内容移动到单个“文件夹”(dir)中。

在这个特定的示例中,我有数百个需要移动的 .txt 文件。我尝试使用shutil.move()os.rename(),但没有成功。

import os 
import shutil 

current_wkd = os.getcwd()
print(current_wkd)

# make sure that these directories exist

dir_src = current_wkd

dir_dst = '.../Merged/out'

for root, dir, files in os.walk(top=current_wkd):
    for file in files:
        if file.endswith(".txt"):  #match files that match this extension
            print(file)
            #need to move files (1.txt, 2.txt, etc) to 'dir_dst'
            #tried: shutil.move(file, dir_dst) = error

如果有办法移动目录的所有内容,我也会对如何做到这一点感兴趣。

非常感谢您的帮助!谢谢。

这里是文件目录和内容

current_wk == ".../Merged 

current_wk有:

 Dir1 
 Dir2 
 Dir3..
 combine.py # python script file to be executed 

在每个目录中都有数百个.txt文件。

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    需要简单的路径数学来精确地找到源文件和目标文件。

    import os
    import shutil
    
    src_dir = os.getcwd()
    dst_dir = src_dir + " COMBINED"
    
    for root, _, files in os.walk(current_cwd):
        for f in files:
            if f.endswith(".txt"):
                full_src_path = os.path.join(src_dir, root, f)
                full_dst_path = os.path.join(dst_dir, f)
                os.rename(full_src_path, full_dst_path)
    

    【讨论】:

    • 那行不通。它只会移动当前目录内容== combine.py。 (它会给出回溯错误 - 找不到 .txt 文件)。谢谢!
    【解决方案2】:

    你必须准备好源文件的完整路径,并确保dir_dst存在。

    for root, dir, files in os.walk(top=current_wkd):
        for file in files:
            if file.endswith(".txt"):  #match files that match this extension
                shutil.move(os.path.join(root, file), dir_dst)
    

    【讨论】:

      猜你喜欢
      • 2017-07-20
      • 2017-01-14
      • 1970-01-01
      • 2017-11-11
      • 2023-04-07
      • 2016-10-09
      • 1970-01-01
      • 2020-05-21
      • 2020-05-01
      相关资源
      最近更新 更多