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 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']
上一篇:
Python3檔方法
下一篇:
Python3 os檔目錄的方法