Python os.rmdir()方法

2019-10-16 23:05:05

Python的rmdir()方法刪除目錄路徑。它僅在目錄為空時才起作用,否則引發OSError異常。

語法

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

os.rmdir(path)

引數

  • path - 這是需要刪除的目錄的路徑。

返回值

  • 此方法不返回任何值。

範例

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

# !/usr/bin/python3
import os, sys
os.chdir("d:\\tmp")

# listing directories
print ("the dir is: %s" %os.listdir(os.getcwd()))

# removing path
os.rmdir("newdir")

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

當執行上述程式時,它會產生以下結果 -

the dir is: [
   'Applicationdocs.docx', 'book.zip', 
   'Java Multiple Inheritance.html', 'Java Multiple Inheritance_files', 
   'java.ppt', 'newdir', 'python2'
]

Traceback (most recent call last):
   File "test.py", line 8, in <module>
   os.rmdir("newdir")
OSError: [WinError 145] The directory is not empty: 'newdir'

出現錯誤是因為「newdir」目錄不為空。 如果’newdir‘是一個空目錄,那麼這將產生以下結果 -

the dir is: [
   'Applicationdocs.docx', 'book.zip', 
   'Java Multiple Inheritance.html', 'Java Multiple Inheritance_files', 
   'java.ppt', 'newdir', 'python2'
]

the dir is: [
   'Applicationdocs.docx', 'book.zip', 
   'Java Multiple Inheritance.html', 'Java Multiple Inheritance_files',  
   'java.ppt', 'python2'
]