简体   繁体   中英

I am having so much trouble in creating/adding to the files in python

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM