Python| os.removedirs() 方法
Python中的OS 模块提供了与操作系统交互的功能。操作系统属于 Python 的标准实用程序模块。该模块提供了一种使用操作系统相关功能的可移植方式。
os 模块中的所有函数在文件名和路径无效或不可访问的情况下,或具有正确类型但操作系统不接受的其他参数的情况下引发OSError 。
Python中的os.removedirs()
方法用于递归删除目录。如果指定路径中的叶子目录被成功删除,则os.removedirs()
尝试连续删除路径中提到的每个父目录,直到引发错误。引发的错误被忽略,因为通常会引发错误,因为要删除的目录不为空。
例如考虑以下路径:
'/home/User/Documents/foo/bar/baz'
在上面的路径中, os.removedirs()
方法将首先尝试删除叶目录,即'baz' 。如果叶子目录'baz'被成功删除,那么方法将尝试删除'/home/User/Documents/foo/bar'然后'/home/User/Documents/foo/'然后'/home/User/Documents'直到引发错误。要删除的目录应该是空的。
Syntax: os.removedirs(path)
Parameter:
path: A path-like object representing a file path. A path-like object is either a string or bytes object representing a path.
Return Type: This method does not return any value.
# Python program to explain os.removedirs() method
# importing os module
import os
# Leaf Directory name
directory = "baz"
# Parent Directory
parent = "/home/User/Documents/foo/bar"
# Path
path = os.path.join(parent, directory)
# Remove the Directory
# "baz"
os.removedirs(path)
print("Directory '%s' has been removed successfully" %directory)
# All parent directory
# of 'baz' will be also
# removed if they are empty
Directory 'baz' has been removed successfully
# Python program to explain os.removedirs() method
# importing os module
import os
# If the specified path
# is not a directory
# then 'NotADirectoryError'
# exception will be raised
# If the specified path
# is not an empty directory
# then an 'OSError'
# will be raised
# If there is any
# permission issue while
# removing the directory
# then the 'PermissionError'
# exception will be raised
# similarly if specified path
# is invalid an 'OSError'
# will be raised
# Path
path = '/home/User/Documents/ihritik/file.txt'
# Try to remove
# the specified path
os.removedirs(path)
Traceback (most recent call last):
File "removedirs.py", line 33, in
os.removedirs(path)
File "/usr/lib/python3.6/os.py", line 238, in removedirs
rmdir(name)
NotADirectoryError: [Errno 20] Not a directory: '/home/User/Documents/ihritik/file.txt'
# Python program to explain os.removedirs() method
# importing os module
import os
# Path
path = '/home/User/Documents/ihritik/file.txt'
# Try to remove
# the specified path
try:
os.removedirs(path)
print("Director removed successfully")
# If path is not a directory
except NotADirectoryError:
print("Specified path is not a directory.")
# If permission related errors
except PermissionError:
print("Permission denied.")
# for other errors
except OSError as error:
print(error)
print("Directory can not be removed")
Specified path is not a directory.
参考: https://docs。 Python.org/3/library/os.html