刪除目錄下的檔案,刪除空資料夾

2021-09-01 11:31:20 字數 1410 閱讀 4702

1.刪除目錄下的所有檔案

#coding:gbk

import os

defdel_nouse_file

(filepath)

:#刪除路徑下的所有檔案

filelist = os.listdir(filepath)

#獲取目錄名列表

for i in filelist:

#遍歷根目錄

filetmp = os.path.join(filepath,i)

#連線目錄與檔名

if os.path.isdir(filetmp)

:#判斷是否為目錄

del_nouse_file(filetmp)

#遞迴刪除目錄中的檔案

else

: os.remove(filetmp)

#刪除檔案

cur_path = os.getcwd(

)#獲取當前路徑

cur_path +=

'\\testfile'

del_nouse_file(cur_path)

print

(cur_path)

2.刪除目錄下的空資料夾

#coding:gbk

import os

defdel_empty_file

(filepath)

:#刪除路徑下的所有空資料夾

isdir = os.path.isdir(filepath)

#判斷是否是資料夾

ifnot isdir:

#不是資料夾直接返回

return

filelist = os.listdir(filepath)

#獲取目錄名列表

for i in filelist:

#遍歷根目錄

filetmp = os.path.join(filepath,i)

#連線目錄與檔名

if os.path.isdir(filetmp)

:#判斷是否為目錄

for d in os.listdir(filetmp)

:#遍歷目錄中的檔案

del_empty_file(os.path.join(filetmp,d))if

not os.listdir(filetmp)

:#判斷是否為空目錄

os.rmdir(filetmp)

#刪除資料夾

cur_path = os.getcwd(

)#獲取當前路徑

cur_path +=

'\\testfile'

del_empty_file(cur_path)

print

('path:'

,cur_path)

python 刪除資料夾 刪除非空資料夾

一般刪除檔案時使用os庫,然後利用os.remove path 即可完成刪除,如果刪除空資料夾則可使用os.removedirs path 即可,但是如果需要刪除整個資料夾,且資料夾非空時使用os.removedirs path 就會報錯了,此時可以使用shutil庫,該庫為python內建庫,是乙...

刪除目錄(資料夾)以及目錄下的檔案

刪除目錄 資料夾 以及目錄下的檔案 param spath 被刪除目錄的檔案路徑 return 目錄刪除成功返回true,否則返回false public static boolean deletedirectory string spath file dirfile new file spath ...

MFCS刪除資料夾,非空資料夾

bool isdirectory lpctstr pstrpath 去除路徑末尾的反斜槓 cstring strpath pstrpath if strpath.right 1 t cfilefind finder bool bret finder.findfile strpath if bret ...