The easiest solution isn't through python; its through the shell. From the first line of your file (#!/usr/bin/python
) I'm guessing you're on a UNIX system. Just use print
statements like you normally would, and don't open the file at all in your script. When you go to run the file, instead of
./script.py
to run the file, use
./script.py > <filename>
where you replace <filename>
with the name of the file you want the output to go in to. The >
token tells (most) shells to set stdout to the file described by the following token.
One important thing that needs to be mentioned here is that "script.py" needs to be made executable for ./script.py
to run.
So before running ./script.py
,execute this command
chmod a+x script.py
(make the script executable for all users)