6

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

Galilsnap
  • 426
  • 2
  • 7
  • 12

4 Answers4

8

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.

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
dmarth
  • 156
  • 3
  • Thanks a bunch, you really helped me. I was making a command-line and i wanted users to change their username and password from the regular "root" and "alpine". – Galilsnap Jun 10 '10 at 05:36
  • Just in case you don't already know it: http://docs.python.org/py3k/library/getpass.html – dmarth Jun 10 '10 at 05:50
  • well, I want to stick to my plan, I already spent quite a lot of hours making it, it will be up on my website soon for developers. Thanks for the link though! – Galilsnap Jun 10 '10 at 06:32
4

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)
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
kumar
  • 2,696
  • 3
  • 26
  • 34
  • Thanks, but I am using Python 3.1.2, and raw_input unfortunately got thrown out >> still works with Python 2 though! Thanks! – Galilsnap Jun 10 '10 at 05:22
  • @Galilsnap: in python 3, input() is the equivalent of raw_input() – Nas Banov Jun 10 '10 at 06:06
  • @Nas Banov: Technically, no. raw_input sends the input right back to the user, or in this case, the variable – Galilsnap Jun 25 '10 at 06:25
  • https://stackoverflow.com/a/30991566/4440053 raw_input() was renamed to input(). Old py2 input() tried to resolve the input, returning an int if possible, as an example. py3 input() = py2 raw_input() always returns the string (in the default encoding, unless stated). – mazunki Mar 29 '19 at 13:07
1

Try Something Like This.

#Getting Where To Save File
where = raw_input('Where Do You Want To Save Your File? ')

#Getting What To Write To File
text = raw_input('What Do You Want To Write To Your File? ')

#Actually Writing It
saveFile = open(where, 'w')
saveFile.write(text)
saveFile.close()
0

Try this out as this also places your input lines each on a new line.

filename = "temp.txt"
with open(filename, "w") as f:
  while True:
      try:
          f.write(input())
          f.write("\n")
      except EOFError:
          break
Shubham Saroj
  • 290
  • 2
  • 12