I want to store the inputs in my text file every time I run it. But when I run the script the old inputs gets deleted! how can I fix this?
sample code:
name = input('Enter name: ')
f = open('test.txt', 'w')
f.write(name)
f.close()
I want to store the inputs in my text file every time I run it. But when I run the script the old inputs gets deleted! how can I fix this?
sample code:
name = input('Enter name: ')
f = open('test.txt', 'w')
f.write(name)
f.close()
You should open the file in append mode:
f = open('test.txt', 'at')
Notice the at
, meaning append text
. You have w
mode, meaning write text
(text is default), which first truncates the file. This is why your old inputs got deleted.
With the 'w' in the open() you create a new empty file everytime. use open('test.txt', 'a+')
Also I would suggest you use the with statement:
name = input('Enter name: ')
with open('test.txt', 'a+') as file:
file.write(name)
write the additional text in append mode
f = open('test.txt', 'a')
'w' is write mode and so deletes any other data before rewriting any new data