【发布时间】:2021-08-02 01:40:16
【问题描述】:
正如标题一样,添加 try / except 块后,删除时没有创建文件一切正常,可能是什么原因? 该程序的任务是创建一个包含当前时间、日期等的文件,在异常块中,想要显示一条消息,这样相同的文件就不会被创建两次。
import datetime
def file():
try:
filename = datetime.datetime.now()
with open(filename.strftime("%Y%m%d-%H%M%S") + ".txt", "w") as file:
file.write("")
file()
except FileExistsError:
print("file already exists")
【问题讨论】:
-
如果文件已经存在,
open()不会引发异常。它只是覆盖它。
标签: python file date exception