Python os.remove() 函数用于删除文件。
语法
os.remove(path)参数
path:要删除的文件路径。
返回值
无返回值(返回 None)。文件不存在抛 FileNotFoundError。
示例
import os
# 建个文件再删
with open("tmp.txt", "w") as f:
f.write("hi")
os.remove("tmp.txt")
print(os.path.exists("tmp.txt")) # False
# 文件不存在会抛 FileNotFoundError
if os.path.exists("maybe.txt"):
os.remove("maybe.txt")注意事项
删除前先 os.path.exists 判断,避免 FileNotFoundError。