當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python 3 os.rmdir()用法及代碼示例


描述

方法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.htm', '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.htm', 'Java Multiple Inheritance_files', 
   'java.ppt', 'newdir', 'python2'
]

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

相關用法


注:本文由純淨天空篩選整理自 Python 3 - os.rmdir() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。