簡體   English   中英

將文件從多個目錄移動到單個目錄

[英]Move files from multiple directories to single directory

我正在嘗試使用os.walk()模塊來遍歷多個目錄,並將每個目錄的內容移動到單個“文件夾”(目錄)中。

在此特定示例中,我有數百個需要移動的.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文件。

需要簡單的路徑數學才能精確地找到源文件和目標文件。

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)

您必須准備源文件的完整路徑,並確保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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM