Home > Software engineering >  Getting a "File doesn't exist" error when trying to create a file
Getting a "File doesn't exist" error when trying to create a file

Time:11-09

I am trying to write to a file that doesn't exist. I was told that when using "w" it would create the file if it doesn't exist. However this did not work and returned an error. I then added a line using "x" to create the file. This still returned an error.

Here is the error:

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'

Here is the code:

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()

CodePudding user response:

Since today is a string containing / characters, day = open(today ".txt", "x") will read this string as a path to create the file in. Your today variable contains 6/11/2021, so it will look for the directory structure 6/11 and in that folder it will try to create the file 2021.txt. Since he can't find those directories, the instruction will fail. You can try to format your file name 6-11-2021.txt. If you do want to use the directories, you can parse today and create directories using os.mkdir

  • Related