67

I have searched Google, Stack Overflow and my Python users guide and have not found a simple, workable answer for the question.

I created a file c:\goat.txt on a Windows 7 x64 machine and am attempting to print "test" to the file. I have tried the following based on examples provided on StackOverflow:

At this point I don't want to use the log module since I don't understand from the documentation of to create a simple log based upon a binary condition. Print is simple however how to redirect the output is not obvious.

A simple, clear example that I can enter into my interperter is the most helpful.

Also, any suggestions for informational sites are appreciated (NOT pydocs).

import sys
print('test', file=open('C:\\goat.txt', 'w')) #fails
print(arg, file=open('fname', 'w')) # above based upon this
print>>destination, arg

print>> C:\\goat.txt, "test" # Fails based upon the above
wjandrea
  • 28,235
  • 9
  • 60
  • 81
surfdork
  • 671
  • 1
  • 5
  • 4
  • 3
    Also, What tutorial are you using? "searched for hours with no result " should be replaced by "did the tutorial for hours". Have you cracked open any tutorial? If so, which one? – S.Lott Nov 05 '10 at 23:33

8 Answers8

128

If you're on Python 2.5 or earlier, open the file and then use the file object in your redirection:

log = open("c:\\goat.txt", "w")
print >>log, "test"

If you're on Python 2.6 or 2.7, you can use print as a function:

from __future__ import print_function
log = open("c:\\goat.txt", "w")
print("test", file = log)
log.close()

If you're on Python 3.0 or later, then you can omit the future import.

If you want to globally redirect your print statements, you can set sys.stdout:

import sys
sys.stdout = open("c:\\goat.txt", "w")
print ("test sys.stdout")
Vince Hall
  • 46
  • 1
  • 6
Eli Courtwright
  • 186,300
  • 67
  • 213
  • 256
  • 1
    Importing this print function makes my other print statements error out. print "Starting LfD..." ^ SyntaxError: invalid syntax – BenB Apr 02 '13 at 00:38
  • 3
    @BenBlumer: That's a good point; you should only do the future import of the print function in a file where you're willing to convert ALL of your print statements to function calls. – Eli Courtwright Apr 02 '13 at 00:46
  • 12
    To reset back to stdout, use the code: `sys.stdout = sys.__stdout__` – Chee Loong Soon Feb 26 '17 at 07:34
  • 1
    Actually, in 3.0 or later, you can supply the file as a keyword arg: `with open('myfile','w') as f: print("my example", file=f)` – JellicleCat Mar 04 '18 at 04:09
54

To redirect output for all prints, you can do this:

import sys
with open('c:\\goat.txt', 'w') as f:
    sys.stdout = f
    print "test"
Matthias
  • 4,481
  • 12
  • 45
  • 84
kolobos
  • 908
  • 7
  • 12
  • 27
    Afterwards you can set set stdout back to original state with: `sys.stdout = sys.__stdout__` – user673592 May 15 '13 at 14:12
  • 2
    its better to re assign `sys.stdout` its default value as mentioned here http://stackoverflow.com/a/7152903/1054978 – Mourya Dec 15 '16 at 10:36
20

A slightly hackier way (that is different than the answers above, which are all valid) would be to just direct the output into a file via console.

So imagine you had main.py

if True:
    print "hello world"
else:
    print "goodbye world"

You can do

python main.py >> text.log

and then text.log will get all of the output.

This is handy if you already have a bunch of print statements and don't want to individually change them to print to a specific file. Just do it at the upper level and direct all prints to a file (only drawback is that you can only print to a single destination).

Tristan Tao
  • 855
  • 11
  • 29
  • So in addition to this I added a "before launch" script in the run configuration from PyCharm which copies the content of text.log/output.log to a file "concatenated_output.log" before python overwrites the old text.log/output.log. This way you have a working history log (the logging package did not work in my case). tip: Make sure you print the date+time somewhere in your output – Harm Campmans Sep 11 '19 at 09:12
7

Building on previous answers, I think it's a perfect use case for doing it (simple) context manager style:

import sys

class StdoutRedirection:
    """Standard output redirection context manager"""

    def __init__(self, path):
        self._path = path

    def __enter__(self):
        sys.stdout = open(self._path, mode="w")
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        sys.stdout.close()
        sys.stdout = sys.__stdout__

and then:

with StdoutRedirection("path/to/file"):
    print("Hello world")

Also it would be really easy to add some functionality to StdoutRedirection class (e.g. a method that lets you change the path)

z33k
  • 3,280
  • 6
  • 24
  • 38
3

Usinge the file argument in the print function, you can have different files per print:

print('Redirect output to file', file=open('/tmp/example.log', 'w'))
Frederico Martins
  • 1,081
  • 1
  • 12
  • 25
2

simple in python 3.6

o = open('outfile','w')

print('hello world', file=o)

o.close()

I was looking for something like I did in Perl

my $printname = "outfile"

open($ph, '>', $printname)
    or die "Could not open file '$printname' $!";

print $ph "hello world\n";
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
clint
  • 21
  • 3
1
from __future__ import print_function
log = open("s_output.csv", "w",encoding="utf-8")
for i in range(0,10):
   print('\nHeadline: '+l1[i], file = log)

Please add encoding="utf-8" so as to avoid the error of " 'charmap' codec can't encode characters in position 12-32: character maps to "

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Sijin John
  • 492
  • 7
  • 15
-2

Redirect sys.stdout to an open file handle and then all printed output goes to a file:

import sys
filename  = open("outputfile",'w')
sys.stdout = filename
print "Anything printed will go to the output file"
fatal_error
  • 5,457
  • 2
  • 18
  • 18
  • 2
    When I run "sys.stdout = filename", the program freezes, not sure what is going wrong. – Jiang Xiang Apr 12 '16 at 21:38
  • perhaps stdout must be assigned to the buffer's pointer itself instead of to a reference. – dopatraman Feb 07 '17 at 23:52
  • 2
    Don't try to reassign sys.stdout if you are interactively typing into the python interpreter, because you'll no longer see any output from the interpreter. Because it uses stdout. Also - don't saw off any branches you are sitting on. :-) – BobDoolittle May 05 '17 at 21:43