2015-05-17 118 views
0

我試圖使用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文件。

回答

0

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

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) 
+0

這是行不通的。它只會移動當前目錄內容== combine.py。 (它會給回溯錯誤 - 無法找到.txt文件)。謝謝! – Novice

0

您必須準備源文件的完整路徑,並確保存在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) 
相關問題