Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redirect the output of print to a TXT file

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
like image 735
surfdork Avatar asked Nov 05 '10 23:11

surfdork


People also ask

How do I print a .TXT file?

Once you've got Notepad's settings right, try this trick: Open Windows Explorer and right-click a text file. On the context menu that appears, click Print. You no longer need to open Notepad first to tell it your preferences. Notepad remembers them for you.

How do I save Python output to a text file?

First, open the text file for write (or append) using the open() function. Second, write to the text file using the write() or writelines() method. Third, close the file using the close() method.


7 Answers

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")
like image 151
Eli Courtwright Avatar answered Oct 12 '22 23:10

Eli Courtwright


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"
like image 31
kolobos Avatar answered Oct 13 '22 00:10

kolobos


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).

like image 27
Tristan Tao Avatar answered Oct 12 '22 22:10

Tristan Tao


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)

like image 21
z33k Avatar answered Oct 13 '22 00:10

z33k


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'))
like image 32
Frederico Mateus Martins Avatar answered Oct 12 '22 22:10

Frederico Mateus Martins


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";
like image 26
clint Avatar answered Oct 13 '22 00:10

clint


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 "

like image 25
Sijin John Avatar answered Oct 12 '22 22:10

Sijin John