首页 > Python资料 博客日记

Python os.rmdir()方法

2023-08-07 15:16:13Python资料围观259

本篇文章分享Python os.rmdir()方法,对你有帮助的话记得收藏一下,看Python资料网收获更多编程知识

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'
]

版权声明:本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:jacktools123@163.com进行投诉反馈,一经查实,立即删除!

标签:

相关文章

本站推荐