Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Text Document (Python) [closed]

Tags:

python

text

save

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?

like image 551
Billjk Avatar asked Feb 14 '12 21:02

Billjk


People also ask

How do you close a text file in Python?

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.

What does close () do in Python?

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.

Do Python files need to be closed?

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.


2 Answers

f = open('file.txt','w')
a = input('is python good?')
f.write('answer:'+str(a))
f.close()

Easy no? :)

like image 55
ingframin Avatar answered Sep 19 '22 13:09

ingframin


with open('spam.txt', 'a') as f:
    f.write(string_output)
like image 34
Fred Avatar answered Sep 20 '22 13:09

Fred