rawse
rawse

Reputation: 5

How to redirect a specific print statement to a text file in python

I am using the below statements to redirect the output of python program to a log_file and it works.

import sys
sys.stdout = open(log_file, 'a', buffering=1)

But, I would like to pass one or two specific print statements to another flat file(let's suppose sample_file.txt). How can I do that ?

Upvotes: 0

Views: 189

Answers (4)

bluesummers
bluesummers

Reputation: 12607

Elegant solution would be using a context manager in the following manner

print("hello")  # Prints to the console

with log_to_file(sys, LOG_FILE_PATH):
    print("hello")  # Prints to the file

print("hello")  # Prints to the console

To build this context manager will be using the following code

from contextlib import contextmanager
import sys

@contextmanager
def log_to_file(sys, LOG_FILE_PATH):
    log_file = open(LOG_FILE_PATH, 'a')
    sys.stdout = log_file
    yield
    log_file.close()
    sys.stdout = sys.__stdout__

Now you can decide where to write every time simply by passing a different file path and your code will be clean and Pythonic

Upvotes: 0

dawg
dawg

Reputation: 103814

On older Python's, you can use the 'chevron print' form of the print statement to print from a specific print statement to a file:

Python 2.7.13 (default, Dec 19 2016, 07:22:39) 
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> f=open('/tmp/file.txt','a')
>>> print "hello"
hello
>>> print >>f, 'hello'
>>> f.close()
>>> open('/tmp/file.txt').read()
'hello\n'

The form print >>fh prints what follows to the file handle fh

Or import the print function in Python 2 to get the ability to add a file handle to the print.

Upvotes: 1

Ahasanul Haque
Ahasanul Haque

Reputation: 11134

If you are using python3, you can optionally pass a fileobject to your print function. Like this:

>>> f = open('sample_file.txt', 'w')
>>> print("hello", file = f)
>>> print("hello1", file = f)
>>> print("hello2", file = f)
>>> f.close()

Or, even better, use context manager.

>>> with open('etc.txt','w') as f:
...     print("hello", file = f)
...     print("hello2", file = f)
...     print("hello2", file = f)

In python2, you can use this feature as well. But you need to import the print() function from python3. Add this import statement.

from __future__ import print_function 

Upvotes: 1

HunterM267
HunterM267

Reputation: 309

Assuming you wanted to append new lines to an existing text file, you could modify your code as such, quite simply:

import sys
sys.stdout = open(log_file, 'a', buffering=1)
with open("sample_file.txt", "a") as f:
    f.write("line 1\n")
    f.write("line 2\n")

Note that the file "sample_file.txt" will be edited in whatever folder/directory the Python file is run in, unless you change it to specify a full (or relative) path.

Upvotes: 0

Related Questions