2015-07-10 163 views
2

我有一個函數:爲什麼shutil.copytree不能將源文件複製到目標文件?

def path_clone(source_dir_prompt, destination_dir_prompt) : 
    try: 
     shutil.copytree(source_dir_prompt, destination_dir_prompt) 
     print("Potentially copied?") 
    except OSError as e: 
     # If the error was caused because the source wasn't a directory 
     if e.errno == errno.ENOTDIR: 
      shutil.copy(source_dir_prompt, destination_dir_prompt) 
     else: 
      print('Directory not copied. Error: %s' % e) 

爲什麼會失敗,輸出:

Directory not copied. Error: [Errno 17] File exists: '[2]' 

source目錄中的文件/目錄是否存在。我的destination文件夾存在,但是當我運行這個,沒有文件被複制,它擊中我的else語句。

我也嘗試將兩個文件夾的權限設置爲chmod 777以避免unix權限錯誤,但這也沒有解決問題。

任何幫助,非常感謝。謝謝。

+0

你想發生什麼目錄存在? –

+0

@PadraicCunningham - 基本覆蓋文件。 – CodeTalk

回答

0

爲copytree的shutil文檔說

遞歸複製在SRC紮根整個目錄樹。由dst命名的目標目錄不能存在;它將被創建以及丟失的父目錄。使用copystat()複製目錄的權限和時間,使用shutil.copy2()複製單個文件。

使用copytree時,您需要確保src存在且dst不存在。即使頂級目錄中不包含任何內容,copytree也不起作用,因爲它不需要在dst中創建頂級目錄本身。

+0

刪除目標目錄後,仍然收到相同的錯誤...。 – CodeTalk

1

我感謝你們所有的人試圖幫助我,顯然我發現了一種適用於我的情況的方式,並在下面張貼以防止某人某天解決此問題(並且不花費幾個小時嘗試得到它的工作) - 享受:

try: 
    #if path already exists, remove it before copying with copytree() 
    if os.path.exists(dst): 
     shutil.rmtree(dst) 
     shutil.copytree(src, dst) 
except OSError as e: 
    # If the error was caused because the source wasn't a directory 
    if e.errno == errno.ENOTDIR: 
     shutil.copy(source_dir_prompt, destination_dir_prompt) 
    else: 
     print('Directory not copied. Error: %s' % e) 
相關問題