Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Take user input and put it into a file in Python?

Tags:

python

I must have skipped a page or two by accident during my PDF Tutorials on Python commands and arguments, because I somehow cannot find a way to take user input and shove it into a file. Don't tell me to try and find solutions online, because I did. None made sense to me.

EDIT: I am using Python 3.1.2, sorry for forgetting

like image 410
Galilsnap Avatar asked Dec 23 '22 02:12

Galilsnap


2 Answers

Solution for Python 3.1 and up:

filename = input("filename: ")
with open(filename, "w") as f:
  f.write(input())

This asks the user for a filename and opens it for writing. Then everything until the next return is written into that file. The "with... as" statement closes the file automatically.

like image 74
dmarth Avatar answered Dec 26 '22 12:12

dmarth


Solution for Python 2

Use raw_input() to take user input. Open a file using open() and use write() to write into a file.

something like:

fd = open(filename,"w")
input = raw_input("user input")
fd.write(input)
like image 44
kumar Avatar answered Dec 26 '22 11:12

kumar