【问题标题】:the file is not created after adding a try / except block in python在 python 中添加 try / except 块后未创建文件
【发布时间】: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


【解决方案1】:

如果文件已经存在,您需要使用“独占”模式引发异常。

def file():

 try:
    filename = datetime.datetime.now()

    with open(filename.strftime("%Y%m%d-%H%M%S") + ".txt", "x"):
        pass
 except FileExistsError:
    print("file already exists")

file()

无需向文件中写入任何内容。由于它不存在,所以它不会有任何东西,所以你不需要覆盖它。

我还删除了对file() 的递归调用,因为它会创建无限递归。函数的调用应该在它定义之后。

另外,不要为变量使用与函数相同的名称。递归调用实际上是试图将打开的文件用作函数。

【讨论】:

  • 你在调用这个函数吗?
【解决方案2】:

您可以使用 os 来检查文件是否已经存在

import datetime
import os


if __name__ == "__main__":
    try:
        filename = datetime.datetime.now().strftime("%Y%m%d-%H%M%S") + ".txt"
        
        if not os.path.exists(filename):
            with open(filename, "w") as file:
                file.write("")
                
        else:
            raise FileExistsError
    
    except FileExistsError:
        print("file already exists")

【讨论】:

  • 是的,您是对的,最好的方法是使用“x”模式访问您在回答中提到的文件。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多