2011-12-08 109 views
5

我在python中遇到了特定的問題。以下是我的文件夾結構。在python中將子文件夾內容移動到父文件夾中

dstfolder/SLAVE1 /從

我想 '從' 文件夾的內容將被移動到 「SLAVE1」(父文件夾)。一旦移動, 「奴隸」文件夾應該被刪除。 shutil.move似乎沒有幫助。

請讓我知道該怎麼做?

+0

你有什麼嘗試? 'shutil.move(src,dst)'文檔說「遞歸移動一個文件或目錄(src)到另一個位置(dst)」,所以它應該起作用。 – jcollado

回答

9

例子:

from os.path import join 
from os import listdir, rmdir 
from shutil import move 

root = 'dstfolder/slave1' 
for filename in listdir(join(root, 'slave')): 
    move(join(root, 'slave', filename), join(root, filename)) 
rmdir(root) 
+0

感謝tito,微小的變化和它的工作!抱歉不能投票,因爲我的聲望很低:-( –

+0

你不能upvote,但你可以驗證迴應:) – tito

+0

也可以使用, 移動父文件夾內容到一個新的子文件夾讓我們說你需要將dir1/*移至dir1/dir2。所以你可以做, 'shutil.move(「dir1」,「dir2)' 'shutil.move(」dir2「,oa.path.join(」dir1「,」dir2「)' –

-2

也許你可以進入字典奴隸,然後

exec system('mv .........') 

它將工作不是嗎?使用的操作系統和shutil模塊

+0

這個答案是特定於POSIX操作系統的,並且會導致代碼的便攜性降低。 – jhrf

0

的問題可能與你在shutil.move功能

指定的路徑試試這個代碼

import os 
import shutil 
for r,d,f in os.walk("slave1"): 
    for files in f: 
     filepath = os.path.join(os.getcwd(),"slave1","slave", files) 
     destpath = os.path.join(os.getcwd(),"slave1") 
     shutil.copy(filepath,destpath) 

shutil.rmtree(os.path.join(os.getcwd(),"slave1","slave")) 

貼吧到dst文件夾中的.py文件中。即slave1和這個文件應該保持並排。然後運行它。爲我工作

+0

另外檢查你是否有所需的權限也是如此 – Pulimon

0

我需要一些更通用的東西,即將所有[sub] +文件夾中的所有文件移動到根文件夾中。

例如入手:

root_folder 
|----test1.txt 
|----1 
    |----test2.txt 
    |----2 
      |----test3.txt 

而且結了:

root_folder 
|----test1.txt 
|----test2.txt 
|----test3.txt 

快速遞歸函數的伎倆:

import os, shutil, sys 

def move_to_root_folder(root_path, cur_path): 
    for filename in os.listdir(cur_path): 
     if os.path.isfile(os.path.join(cur_path, filename)): 
      shutil.move(os.path.join(cur_path, filename), os.path.join(root_path, filename)) 
     elif os.path.isdir(os.path.join(cur_path, filename)): 
      move_to_root_folder(root_path, os.path.join(cur_path, filename)) 
     else: 
      sys.exit("Should never reach here.") 
    # remove empty folders 
    if cur_path != root_path: 
     os.rmdir(cur_path) 

你通常會與稱它爲root_pathcur_path的相同說法,例如move_to_root_folder(os.getcwd(),os.getcwd())如果你想在Python環境中嘗試它。

相關問題