0

How would I go about sending the output of a print command to a new file? I have a python script where I need to redirect the output at the end of the print statement to a file but I can't seem to find a way to accomplish the redirect. Why doesn't "print (stuff to be redirected) > newfile.txt" work?

Any help is appreciated!

Russ
  • 103
  • 9
  • 1
    Redirecting with `>` is for the command line. For example, `C:\Users\russ\Documents> py mymodule.py > output.txt`. Telling your Python program itself to create a file is a different process (see alfasin's comment, above). – TigerhawkT3 Mar 29 '15 at 03:23

1 Answers1

0

As mentioned in this post, you could set the standard output to a file object.

import sys
sys.stdout = open('file', 'w')

Then, all your print statements should go directly to that file.

Community
  • 1
  • 1
Julien Spronck
  • 15,069
  • 4
  • 47
  • 55