python 遞迴刪除資料夾 遞迴複製資料夾

2021-10-08 08:31:27 字數 1763 閱讀 4281

學過python os模組的人都知道python中的rmdir()函式只能刪除乙個空的資料夾,而remove()函式也只能刪除單個的檔案,沒有乙個現成的方法來刪除乙個資料夾(裡面有檔案)

所以我們要借助遞迴去刪除乙個資料夾中的每乙個檔案(或者資料夾)

下面是**:

# 遞迴刪除資料夾

import os

defdel_dir

(path)

:#先將資料夾中的檔案遍歷一遍

forfile

in os.listdir(path)

:#先判斷檔案的型別(是否是檔案)

file

= os.path.join(path,

file

)if os.path.isfile(

file):

#如果是檔案

os.remove(

file

)else

:#如果是資料夾

del_dir(

file

) os.rmdir(

file

) os.rmdir(path)

具體的想法就是如果是檔案型別,那就直接使用remove()函式直接刪除檔案,如果是資料夾,就遞迴呼叫自己(再次遍歷這個資料夾中的每乙個檔案,再次進行上述的判斷)

同樣的複製資料夾也是同樣的思想

# 遞迴複製資料夾

import os

# 簡單的複製和貼上檔案

defcopy

(src,target)

: rstream =

open

(src,

'rb'

) wstream =

open

(target,

'wb'

) temp = rstream.readline(

)while temp:

wstream.write(temp)

temp = rstream.readline(

) rstream.close(

) wstream.close(

)# 核心複製函式

defcopy_dir

(src,target)

:#先建立好空的資料夾

os.mkdir(target)

# 遍歷整個資料夾

forfile

in os.listdir(src)

:#判斷檔案型別

file_path = os.path.join(src,

file

)if os.path.isfile(file_path)

:#如果是檔案

old_path = os.path.join(src,

file

) new_path = os.path.join(target,

file

) copy(old_path,new_path)

else

:# 如果是資料夾

new_src = os.path.join(src,

file

) new_target = os.path.join(target,

file

) copy_dir(new_src,new_target)

複製資料夾的操作要比刪除稍微複雜一些,需要有乙個新建資料夾和檔案讀寫複製的操作

遞迴刪除資料夾 python

遞迴刪除資料夾 def myrmdir dirpath 思路 先將資料夾裡面所有的檔案刪除掉,如果是空資料夾,刪除之,遍歷這個資料夾,得到資料夾下面所有的檔案 filename list os.listdir dirpath print filename list 遍歷這個列表,判斷該元素是檔案還是...

遞迴刪除資料夾

只能刪除目錄內的所有檔案,目錄內的目錄未刪除。因為當時os.rmdir 不知道加在哪,好像哪都不對,有知道的請告訴我。import os from os import path def diy remove the path if path.exists the path if path.isdir...

遞迴刪除資料夾

方法名稱 deletefolder 方法描述 遞迴刪除目錄下的所有檔案及子目錄下所有檔案 param dir 將要刪除的檔案目錄 return boolean returns true if all deletions were successful.if a deletion fails,the ...