首页 > 解决方案 > 尝试创建文件时出现“文件不存在”错误

问题描述

我正在尝试写入一个不存在的文件。有人告诉我,如果"w"文件不存在,使用它时会创建该文件。但是,这不起作用并返回了错误。然后我添加了一行"x"用于创建文件。这仍然返回错误。

这是错误:

Traceback (most recent call last):
  File "C:\Users\brain\Documents\Python projects\Calendar\Calendar.py", line 22, in <module>
    day = open(today+".txt", "x")
FileNotFoundError: [Errno 2] No such file or directory: '6/11/2021.txt'

这是代码:

print("You do not have any reminders for today.")
print("Would you like to make some?")
newtoday = input().lower()
if newtoday == "yes":
    filename = open("filenames.txt", "w")
    filename.write(today)
    day = open(today+".txt", "x")
    day.close()
    day = open(today+".txt", "w")
    print("What would you like the title of the reminder to be?")
    title = input()
    print("Add any extra details below e.g. time, place.")
    det = input()
    day.write(title+": "+det, "(x)")
    filename.close()
    day.close()

标签: pythonfile

解决方案


由于today是一个包含/字符的字符串,day = open(today+".txt", "x")将读取此字符串作为在其中创建文件的路径。您的today变量包含6/11/2021,因此它将查找目录结构6/11并在该文件夹中尝试创建文件2021.txt。由于他找不到那些目录,因此指令将失败。您可以尝试格式化您的文件名6-11-2021.txt。如果您确实想使用目录,可以使用os.mkdirtoday解析和创建目录


推荐阅读