0

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 ?

4
  • 1
    You can open a file in append mode and write your data in it: with open("sample_file.txt", "a") as f: f.write("hello world!\n") Commented May 29, 2017 at 2:53
  • 1
    You might want to use the logging module in your project. Commented May 29, 2017 at 3:00
  • python2 or python3? Commented May 29, 2017 at 3:17
  • I am using Python 2.6.6. Commented May 29, 2017 at 3:28

4 Answers 4

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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 

1 Comment

Well, it will. you have to import the function from python3. just add the line from __future__ import print_function among the imports of your file.
0

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.

3 Comments

@rawse - Which version of python are you using? I have run the code in my environment (excluding the log file print), and it works as intended. However, I had forgot to add a new line character to the end of my two lines, which I have corrected.
I have got the syntax error when I tried the same. sys.stdout = open('/opt/test/test_user/data/PLANNING_%s_%s_%s.etab' % (type, period, self.now), 'a', buffering=1) with open('/opt/test/test_user/data/SUB_PLANNING_%s_%s_%s.etab'' % (type, period, self.now), 'a') as e: SyntaxError: invalid syntax
Why not use print rather than write, especially as the question says they wish to "print statements to another file"
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.