Python os.remove()
os模块中的所有函数在文件名和路径无效或不可访问,或其他具有正确类型但操作系统不接受的参数时都会引发OSError。
Python中的os.remove()方法用于删除指定路径的文件。此方法无法删除或删除目录。如果指定的路径是一个目录,则该方法将引发OSError。os.rmdir()可用于删除目录。
语法:os.remove(path,*,dir_fd =None)
参数:
path:表示文件路径的类路径对象。类路径对象是表示路径的字符串或字节对象。
dir_fd(可选):指向目录的文件描述符。这个参数的默认值是None。
如果指定的路径是绝对路径,则忽略dir_fd。
注意:参数列表中的’ * ‘表示以下所有参数(在我们的例子中是’ dir_fd ‘)都是仅关键字参数,可以使用它们的名称提供它们,而不是作为位置参数。
返回类型:此方法不返回任何值。
示例1
使用os.remove()方法来删除一个文件
# Python program to explain os.remove() method
# importing os module
import os
# File name
file = 'file.txt'
# File location
location = "/home/User/Documents"
# Path
path = os.path.join(location, file)
# Remove the file
# 'file.txt'
os.remove(path)
print("%s has been removed successfully" %file)
输出:
file.txt has been removed successfully
示例2
如果指定的路径是一个目录
# Python program to explain os.remove() method
# importing os module
import os
# Path
path = "/home/User/Documents/ihritik"
# Remove the specified
# file path
os.remove(path)
print("% s has been removed successfully" % file)
# if the specified path
# is a directory then
# 'IsADirectoryError' error
# will raised
# Similarly if the specified
# file path does not exists or
# is invalid then corresponding
# OSError will be raised
输出:
Traceback (most recent call last):
File "osremove.py", line 11, in
os.remove(path)
IsADirectoryError: [Errno 21] Is a directory: '/home/User/Documents/ihritik'
示例3
处理使用os.remove()方法时的错误
# Python program to explain os.remove() method
# importing os module
import os
# path
path = '/home/User/Documents/ihritik'
# Remove the specified
# file path
try:
os.remove(path)
print("% s removed successfully" % path)
except OSError as error:
print(error)
print("File path can not be removed")
输出:
[Errno 21] Is a directory: '/home/User/Documents/ihritik'
File path can not be removed