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

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.

Leave a Comment