Lets say I want to create a document out of user-inputted code, called spam.txt
. Assuming I have the user input, say:
input("Is Python Good? ")
How can I save the text, that the user inputted, to a text file, and can one do this?
The close() method of a file object flushes any unwritten information and closes the file object, after which no more writing can be done. Python automatically closes a file when the reference object of a file is reassigned to another file. It is a good practice to use the close() method to close a file.
The close() method closes an open file. You should always close your files, in some cases, due to buffering, changes made to a file may not show until you close the file.
You've learned why it's important to close files in Python. Because files are limited resources managed by the operating system, making sure files are closed after use will protect against hard-to-debug issues like running out of file handles or experiencing corrupted data.
f = open('file.txt','w')
a = input('is python good?')
f.write('answer:'+str(a))
f.close()
Easy no? :)
with open('spam.txt', 'a') as f:
f.write(string_output)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With