0

How can I save output printed in the python terminal to a text file, and how can I specify where it is to be saved to? For example, I know how to do this, but it really doesn't do anything as far as I've noticed:

sys.stdout = open('thefile.txt', 'w')
print "In a file?"

How can I actually get it to write this to a text file, and then be able to find that text file? (Or a file of any other form.)

Ethan Bierlein
  • 3,353
  • 4
  • 28
  • 42

1 Answers1

0

What you have done in your code is correct.

import sys
sys.stdout = open('thefile.txt', 'w')
print "In a file?"
  • import sys - imports the sys module
  • sys.stdout = open('thefile.txt', 'w') - changes the sys.stdout to a writeable ('w') file object so that anything written to stdout is written to that file.
  • print "In a file?" - prints In a file? to stdout, in this case it will be the thefile.txt file.

You can find the text file (thefile.txt) in the directory in which the Python code is in.

Alternatively, you can omit the first 2 lines in the code above (i.e. only have the print statement) and run your python code as follows:

$ python your_python_script.py > thefile.txt

The > redirects stdout to a file. It creates the file if not present, otherwise overwrites it.

Community
  • 1
  • 1
s16h
  • 4,647
  • 1
  • 21
  • 33
  • How could I make it so the user chooses the name of the file? – Ethan Bierlein Apr 10 '14 at 22:28
  • The user can either use the second method and put whatever name they want when they run the script or you can ask for the filename as input in your program. – s16h Apr 10 '14 at 22:39