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'
]
上一篇:
Python os模块方法
下一篇:
Python异常处理