Python os.removedirs()
os模块中的所有函数在文件名和路径无效或不可访问,或其他具有正确类型但操作系统不接受的参数时都会引发OSError。
Python中的os.removedirs()方法用于递归地删除目录。如果成功删除了指定路径中的叶子目录,那么os.removedirs()将尝试依次删除路径中提到的所有父目录,直到出现错误为止。引发的错误会被忽略,因为要删除的目录非空会引发一般的错误。
例如,考虑以下路径:
'/home/User/Documents/foo/bar/baz'
在上面的路径中,os.removedirs()方法将首先尝试删除叶子目录.e ‘ baz ‘。如果叶子目录’ baz ‘被成功删除,那么方法将尝试删除’ /home/User/Documents/foo/bar ‘然后’ /home/User/Documents/foo/ ‘然后’ /home/User/Documents/foo/ ‘直到抛出一个错误。要删除的目录必须为空。
语法:os.removedirs(path)
参数:
path:表示文件路径的类路径对象。类路径对象是表示路径的字符串或字节对象。
返回类型:此方法不返回任何值。
示例1
使用os.removeirs()方法来删除一个空目录树
# 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
示例2
使用os.removeirs()方法时可能出现的错误
# 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'
示例3
处理使用os.removeirs()方法时的错误
# 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