python中remove用法_Python os.remove()用法及代码示例

Python中的OS模块提供了与操作系统进行交互的功能。操作系统属于Python的标准实用程序模块。该模块提供了使用依赖于操作系统的功能的便携式方法。

如果文件名和路径无效或无法访问,或者具有正确类型但操作系统不接受的其他参数,则os模块中的所有函数都会引发OSError。

os.remove()Python中的方法用于删除或删除文件路径。此方法无法删除或删除目录。如果指定的路径是目录,则该方法将引发OSError。os.rmdir()可用于删除目录。

用法: os.remove(path, *, dir_fd = None)

参数:

path:表示文件路径的path-like对象。 path-like对象是表示路径的字符串或字节对象。

dir_fd(可选):引用目录的文件描述符。此参数的默认值为“无”。

如果指定的路径是绝对路径,则dir_fd将被忽略。

Note:参数列表中的“ *”表示以下所有参数(此处为“ dir_fd”)均为keyword-only参数,可以使用其名称而不是位置参数来提供它们。

返回类型:此方法不返回任何值。

代码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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值