python 刪除檔案和資料夾

2021-09-08 11:56:50 字數 810 閱讀 2923

1、刪除檔案

'''刪除檔案 '''

def deletefile(strfilename):

filename = unicode(strfilename, "utf8")

if os.path.isfile(filename):

try:

os.remove(filename)

except:

pass

2、刪除資料夾

'''刪除指定目錄,首先刪除指定目錄下的檔案和子資料夾,然後再刪除該資料夾'''

def delete_file_dir(dirname,flag = true):

if flag:

dirname = unicode(dirname, "utf8")

'''如何是檔案直接刪除'''

if os.path.isfile(dirname):

try:

os.remove(dirname)

except:

pass

elif os.path.isdir(dirname):

'''如果是資料夾,則首先刪除資料夾下檔案和子資料夾,再刪除資料夾'''

for item in os.listdir(dirname):

tf = os.path.join(dirname,item)

'''遞迴呼叫'''

delete_file_dir(tf,false)

try:

os.rmdir(dirname)

except:

pass

3、

Python刪除檔案和資料夾

鏈結 個人總結一下 刪除檔案 os.remove path 如果path是乙個目錄,丟擲 oserror錯誤。如果檔案不錯在或路徑錯誤,也會丟擲錯誤刪除資料夾 os.rmdir dirname os.removedirs dirname 刪除目錄 dirname,要求dirname必須是個空目錄,否...

刪除檔案和資料夾

一 刪除檔案 使用 del 命令,可以檢視幫助資訊 del p f s q a attributes names erase p f s q a attributes names names 指定乙個或數個檔案或目錄列表。萬用字元可被用來 刪除多個檔案。如果指定了乙個目錄,目錄中的所 有檔案都會被刪...

刪除檔案和資料夾

一 刪除檔案 使用 del 命令,可以檢視幫助資訊 del p f s q a attributes names erase p f s q a attributes names names 指定乙個或數個檔案或目錄列表。萬用字元可被用來 刪除多個檔案。如果指定了乙個目錄,目錄中的所 有檔案都會被刪...