python os.removedirs() 和shutil.rmtree()(os.removedirs用于删除非空文件夹和子文件夹、shutil.rmtree用于删除文件夹下所有文件夹和文件)
生活随笔
收集整理的這篇文章主要介紹了
python os.removedirs() 和shutil.rmtree()(os.removedirs用于删除非空文件夹和子文件夹、shutil.rmtree用于删除文件夹下所有文件夹和文件)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- shutil.rmtree()
- os.removedirs()
shutil.rmtree()
shutil.rmtree() 表示遞歸刪除文件夾下的所有子文件夾和子文件。
def rmtree(path, ignore_errors=False, onerror=None):"""Recursively delete a directory tree. 遞歸刪除目錄樹。If ignore_errors is set, errors are ignored; otherwise, if onerroris set, it is called to handle the error with arguments (func,path, exc_info) where func is platform and implementation dependent;path is the argument to that function that caused it to fail; andexc_info is a tuple returned by sys.exc_info(). If ignore_errorsis false and onerror is None, an exception is raised.如果設置了ignore_errors,錯誤將被忽略; 否則,如果設置了onerror,則調用該函數以使用參數(func,path,exc_info)來處理錯誤,其中func與平臺和實現有關; path是導致該函數失敗的參數。 而exc_info是sys.exc_info()返回的元組。 如果ignore_errors為false,onerror為None,則會引發異常。"""因此如果想刪除E盤下某個文件夾,可以用
shutil.rmtree('E:\\myPython\\image-filter\\test', ignore_errors=True)這樣 test 文件夾內的所有文件(包括 test 本身)都會被刪除,并且忽略錯誤。
os.removedirs()
def removedirs(name):"""removedirs(name)Super-rmdir; remove a leaf directory and all empty intermediateones. Works like rmdir except that, if the leaf directory issuccessfully removed, directories corresponding to rightmost pathsegments will be pruned away until either the whole path isconsumed or an error occurs. Errors during this latter phase areignored -- they generally mean that a directory was not empty.超級rmdir; 刪除葉子目錄和所有空的中間目錄。 類似于rmdir的工作方式,不同之處在于,如果成功刪除了葉目錄,將刪除最右邊路徑段所對應的目錄,直到使用完整個路徑或發生錯誤為止。 在后面的階段中的錯誤將被忽略-它們通常意味著目錄不是空的。"""注意:os.removedirs()只能刪除子文件夾中的空文件夾,非空無法刪除,參見:Python學習:糾錯筆記:詳解os.removedirs(path)的正確用法
參考文章:python中的 os.mkdir和os.mkdirs,os.rmdir()和os.removedirs()
總結
以上是生活随笔為你收集整理的python os.removedirs() 和shutil.rmtree()(os.removedirs用于删除非空文件夹和子文件夹、shutil.rmtree用于删除文件夹下所有文件夹和文件)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python os.path.exist
- 下一篇: 如何使用yunyang tensorfl