2009-02-04 79 views
32

我試圖將目錄及其所有內容複製到已存在的路徑。問題是,在os模塊和shutil模塊之間,似乎沒有辦法做到這一點。 shutil.copytree()函數預期目標路徑不存在。如何使用Python將目錄及其內容複製到現有位置?

我正在尋找的確切結果是將整個文件夾結構複製到另一個文件結構上,在發現的任何重複項上無聲覆蓋。在我加入並開始編寫自己的函數來完成此操作之前,我想我會詢問是否有人知道現有的配方或片段是否可以實現此目的。

回答

42

distutils.dir_util.copy_tree你想要做什麼。

Copy an entire directory tree src to a new location dst. Both src and dst must be directory names. If src is not a directory, raise DistutilsFileError. If dst does not exist, it is created with mkpath(). The end result of the copy is that every file in src is copied to dst, and directories under src are recursively copied to dst. Return the list of files that were copied or might have been copied, using their output name. The return value is unaffected by update or dry_run: it is simply the list of all files under src, with the names changed to be under dst.

(在上述網址的更多文檔)

+1

以前沒見過這個,很好找。我唯一需要注意的是它沒有指出哪些文件被覆蓋,哪些文件是重新創建的。然而,只要這不是要求,這看起來很完美。 – 2009-02-04 17:29:57

+0

這是一個不錯的選擇,雖然它需要安裝distutils。沒有這麼大的問題,因爲我們使用pyinstaller將它捆綁到EXE中。 – Soviut 2009-02-04 18:15:56

0

爲什麼不自己實施它使用os.walk

+5

這就是我正在考慮,但我想確保我沒有重新發明輪子。 – Soviut 2009-02-04 18:15:08

0

對於高級別文件操作一樣,使用shutil模塊和你的情況copytree功能。我認爲這比「濫用」失誤更清潔。

更新::忘記了答案,我忽略了OP做的嘗試shutil。

0

你是否在得到「無法創建目錄時,它已經存在」的錯誤? 我不知道有多少愚蠢的是這一點,但我所做的就是爲一條直線插入copytree模塊: 我改變:

def copytree(src, dst, symlinks=False): 
    names = os.listdir(src) 
    os.makedirs(dst) 

到:

def copytree(src, dst, symlinks=False): 
    names = os.listdir(src) 
    if (os.path.isdir(dst)==False): 
     os.makedirs(dst)  

我想我做了一些bluder。如果是這樣,有人可以指出我嗎?對不起,我是很新的蟒蛇:P

相關問題