Python Forum

Full Version: my first file won't create itself
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
name =input("what is your name?")
sipCard =int(input("What is your sip card"))
twoforone =int(input("How many of the two for one deals would you like?"))
            
#monthly record
with open ("MonthlyRecord.txt")as f:
    f.write (name)
    f.write (sipCard)
    f.write (twoforone)
    f.close()

    f = open("MonthlyRecord.txt", "r")
    print(f.read())
Output:
what is your name?mehri What is your sip card123 How many of the two for one deals would you like?3
Error:
Traceback (most recent call last): File "C:/Users/StaR/AppData/Local/Programs/Python/Python311/file.py", line 6, in <module> with open ("MonthlyRecord.txt")as f: FileNotFoundError: [Errno 2] No such file or directory: 'MonthlyRecord.txt'
To make changes so it work,and some improvent.
Some points need w parameter when shall wtite to file.
when use with open don't need to close the file as it automatically done.
name = 'Tom'
sipCard = 5
twoforone = 3

#monthly record
with open("MonthlyRecord.txt", 'w') as fp_out:
    fp_out.write(f'{name}\n{sipCard}\n{twoforone}')

with open("MonthlyRecord.txt", "r") as fp:
    print(fp.read())
Output:
Tom 5 3
Thank you so much!