Python3 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.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文件目录的方法