Python os.removedirs()方法

2019-10-16 23:05:01

Python的removedirs()方法遞回刪除目錄。 如果子目錄成功刪除,則removeirs會嘗試依次刪除路徑中顯示的每個父目錄。如果子目錄無法成功刪除,則引發OSError

語法

以下是removedirs()方法的語法 -

os.removedirs(path)

引數

  • path - 這是將要刪除的路徑。

返回值

  • 此方法不返回任何值。

範例

以下範例顯示了removedirs()方法的用法。

# !/usr/bin/python3
import os, sys

os.chdir("d:\\tmp")
# listing directories
print ("The dir is: %s" %os.listdir(os.getcwd()))

# removing
os.removedirs("home\\monthly\\daily")

# listing directories after removing directory
print ("The dir after removal is:" %os.listdir(os.getcwd()))

編譯並執行上面的程式,將輸出以下結果 -

The dir is: [
   'Applicationdocs.docx', 'book.zip', 'foo.txt', 'home', 
   'Java Multiple Inheritance.html', 'Java Multiple Inheritance_files', 
   'java.ppt', 'ParallelPortViewer', 'test.java'
]
The dir after removal of path : [
   'Applicationdocs.docx', 'book.zip', 'foo.txt', 'home', 
   'Java Multiple Inheritance.html', 'Java Multiple Inheritance_files', 
   'java.ppt', 'ParallelPortViewer'
]