0
date = input("Enter today's date: ")
mood = input("How do you rate your mood today from 1 to 10? ")
thought = input("Lets your thought flow :" + "\n")

with open(f"../SU/{date}.txt", 'w') as file:
    file.write(mood + 2 * "\n")
    file.write(thought + 2 * "\n")

Getting errors:

C:\Users\User\Desktop\PyPro_Jan23_3.10\venv\Scripts\python.exe C:\Users\User\Desktop\PyPro_Jan23_3.10\Bonus\Bonuss8.py 
Enter today's date: 2023/01/01
How do you rate your mood today from 1 to 10? 10
Lets your thought flwo :
fine
Traceback (most recent call last):
  File "C:\Users\User\Desktop\PyPro_Jan23_3.10\Bonus\Bonuss8.py", line 5, in <module>
    with open(f"../SU/{date}.txt", 'w') as file:
FileNotFoundError: [Errno 2] No such file or directory: '../SU/2023/01/01.txt'

Process finished with exit code 1

I am trying to creating a new file while keeping a variable as input the filename that has to be generated in a directory other than than that of the current py file.

Help me with some example of multiple ways of creating file, adding to the existing files.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • @KenLee It's a [formatted string literal](https://docs.python.org/3/tutorial/inputoutput.html#formatted-string-literals). – Unmitigated Jan 01 '23 at 02:22
  • 3
    `2023/01/01.txt` Slashes in filenames are _always_ treated as subdirectories. Did you intend there to be a `2023` directory, and a `01` directory underneath that? – John Gordon Jan 01 '23 at 02:23

2 Answers2

0

This means the directories you have provided don't exist.
also adding '/' would mean that you're looking for a directory.
so First you need to create the folder /SU. and not use forbidden folder name characters mentioned here What characters are forbidden in Windows and Linux directory names? which '/' in your dates include

  • to elaborate. if you don't have the `/SU/` folder you should create it, and when you add a date use a different format like `20230101` or `2023_01_01` instead of `2023/01/01` – Yasser Elbarbay Jan 01 '23 at 02:25
0

You may use the replace command to change all / characters to - so that the file name will not be treated as sub-directory

date = input("Enter today's date: ")
mood = input("How do you rate your mood today from 1 to 10? ")
thought = input("Lets your thought flow :" + "\n")

date = date.replace("/", "-")

with open(f"../SU/{date}.txt", 'w') as file:
    file.write(mood + 2 * "\n")
    file.write(thought + 2 * "\n")
Ken Lee
  • 6,985
  • 3
  • 10
  • 29