python 遞迴刪除檔案 目錄

2021-08-20 17:30:08 字數 1866 閱讀 8738

python 遞迴刪除檔案、目錄本文講述了python實現刪除檔案與目錄的方法。具體實現方法如下:

一、刪除檔案 

os.remove(path) 

刪除檔案 path. 如果path是乙個目錄, 丟擲 oserror錯誤。如果要刪除目錄,請使用rmdir().

remove() 同 unlink() 的功能是一樣的 

my_file = 'foo/bar/baz/test.txt'

if os.path.exists(my_file):

print "存在"

# my_file = 'foo/bar/baz/test.txt'

# 刪除檔案,可使用以下兩種方法。

# 刪除檔案 path. 如果path是乙個目錄, 丟擲 oserror錯誤。如果要刪除目錄,請使用rmdir().

os.remove(my_file) # oserror: [errno 1] operation not permitted: 'foo/bar/baz'

os.unlink(my_file) # oserror: [errno 1] operation not permitted: 'foo/bar/baz'

else:

print 'no such file:%s'%my_file

二、遞迴刪除目錄和檔案

os.removedirs(path) 

遞迴地刪除目錄。類似於rmdir(), 如果子目錄被成功刪除, removedirs() 將會刪除父目錄;但子目錄沒有成功刪除,將丟擲錯誤。 

舉個例子, os.removedirs(「foo/bar/baz」) 將首先刪除 「foo/bar/ba」目錄,然後再刪除foo/bar 和 foo, 如果他們是空的話 

如果子目錄不能成功刪除,將 丟擲 oserror異常

os.rmdir(path) 

刪除目錄 path,要求path必須是個空目錄,否則丟擲oserror錯誤

遞迴刪除目錄和檔案(類似dos命令deletetree): 

複製** **如下:

top='foo/bar/baz'

import os

for root, dirs, files in os.walk(top, topdown=false):

print "root: ", root, " dirs: ", dirs, " files: ",files

'''root: foo/bar/baz/empty/test dirs: files:

root: foo/bar/baz/empty dirs: ['test'] files:

root: foo/bar/baz dirs: ['empty'] files: ['test_bak.txt', 'test.txt']

'''continue

for name in files:

os.remove(os.path.join(root, name))

for name in dirs:

os.rmdir(os.path.join(root, name))

或者

print "***************"

top='foo/bar/baz/empty/test'

# 刪除test這個目錄及其裡面的子目錄和檔案

import shutil

shutil.rmtree(path=top)

print "done"

參考:

python 刪除檔案 目錄

remove 同 unlink 的功能是一樣的 在windows系統中,刪除乙個正在使用的檔案,將丟擲異常。在unix中,目錄表中的記錄被刪除,但檔案的儲存還在。使用os.unlink 和os.remove 來刪除檔案 user local bin python2.7 coding utf 8 im...

遞迴目錄合併或刪除檔案

coding utf 8 合併給定目錄下面的所有檔案,並且生成乙個all.txt 以ab 方式開啟 二進位制 採用遞迴 如果不是檔案 if 則繼續遞迴,如果是檔案 else 則合併資訊。os.path.isdir 判斷給定路徑是否是目錄 os.path.isfile 判斷給定路徑是否是檔案 os.p...

遞迴刪除目錄

include stdafx.h include include include using namespace std void deletedir cstring szpath void recursiondelete cstring szpath int tmain int argc,tcha...