Sitelet https://howtodoinjava.com/python-examples/python-print-to-file/

Python print() to File: file=, redirect_stdout and More

Print to a file in Python with print(file=f), append mode and encoding, contextlib.redirect_stdout(), sys.stdout and shell redirection with > and 2>&1.

Python

To print to a file in Python, we pass an open file object to the file argument of print(); for code we cannot change, we redirect sys.stdout with contextlib.redirect_stdout(), and for a whole script we redirect the output in the shell.

MethodWhen to Use
print(…, file=f)Code we write ourselves prints some lines to a file
contextlib.redirect_stdout()Output of a function or library that prints to the screen, within a block
Reassigning sys.stdoutThe same as above, in older code; needs manual restoring
Shell redirection >All the output of a script, and errors with 2>&1

We look at each method with its output, and at append mode, encoding and buffering, and at logging as the alternative for long-running programs. The examples run on Python 3.14.

1. Print to File using file Argument

The print() function accepts the keyword argument file, whose default None means sys.stdout, the screen. Any object with a write() method works, and a file opened in text mode is the usual target.

with open("demo.txt", "w", encoding="utf-8") as f:
    print("Hello, Python!", file=f)
    print("Total:", 42, file=f)
Hello, Python!
Total: 42

The with block closes the file even when an exception occurs, and encoding=”utf-8″ keeps non-English text intact on every operating system. A file left open with open() alone may lose its last lines if the program crashes.

2. Appending Instead of Overwriting

Mode “w” empties the file each time it is opened, and mode “a” adds new lines at the end, which suits logs and reports that grow over time.

for run in (1, 2):
    with open("runs.txt", "a", encoding="utf-8") as f:
        print("run", run, "finished", file=f)
run 1 finished
run 2 finished

3. Using redirect_stdout() from contextlib Module

The contextlib.redirect_stdout() context manager sends everything printed inside the with block to another file and restores the screen afterwards. It is the right tool when a function or library prints and we cannot add a file argument.

from contextlib import redirect_stdout

def report():
    print("Sales: 120")
    print("Returns: 4")

with open("report.txt", "w", encoding="utf-8") as f, redirect_stdout(f):
    report()
print("This message will be written to the screen.")

After the block, report.txt holds both lines that report() printed.

Sales: 120
Returns: 4

The redirection only affects Python code that writes to sys.stdout. Output from subprocesses or C extensions still goes to the screen, and redirect_stderr() handles error messages in the same way.

4. Redirecting Standard Output Stream to a File

Older code reassigns sys.stdout by hand. It works, but the original stream must be restored in a finally block, or every later print disappears into the file.

import sys

original_stdout = sys.stdout
with open("demo2.txt", "w", encoding="utf-8") as f:
    sys.stdout = f
    try:
        print("This message will be written to a file.")
    finally:
        sys.stdout = original_stdout
print("Back on the screen.")

5. Redirect Script Output to a File

To capture everything a script prints without changing its code, we redirect in the shell. The > operator replaces the file, >> appends, and 2>&1 adds error messages to the same file.

python report.py > output.txt            # standard output only
python report.py >> output.txt           # append
python report.py > output.txt 2>&1       # output and errors
python report.py | tee output.txt        # screen and file (Linux, macOS)

6. Writing a Simple CSV Report with print()

Because print() accepts sep and file together, it can write a small comma-separated report without extra modules, as long as the values contain no commas.

rows = [("tea", 4, 5.0), ("milk", 2, 2.25)]
with open("sales.csv", "w", encoding="utf-8") as f:
    print("item", "qty", "price", sep=",", file=f)
    for row in rows:
        print(*row, sep=",", file=f)
item,qty,price
tea,4,5.0
milk,2,2.25

For values that may contain commas or quotes, the csv module handles the escaping. See Python print() for the other arguments.

7. Print to File FAQs

File output behaves differently from the screen in buffering and in what it accepts.

7.1. Why is the file empty while the program is still running?

File output is buffered and written in blocks. Passing flush=True to print() writes each line at once, which matters for files that another program watches.

7.2. Can print() write to a file opened in binary mode?

No. print() writes strings, so a file opened with “wb” raises TypeError. We open the file in text mode or encode the text and call write() ourselves.

7.3. Should we use print() or logging for log files?

For scripts, print(…, file=f) is fine. Long-running applications use the logging module, which adds timestamps and levels, rotates files and can be configured without changing the code.

8. Conclusion

The file argument is the simplest way to print to a file from our own code, with “a” for appending and encoding=”utf-8″ for safe text. The redirect_stdout() context manager captures output we cannot change, and shell redirection captures a whole script.

9. References

Happy Learning !!

Source Code on Github

Leave a Comment

  1. This was very helpful. It provided the best solution for a problem I was trying to solve on my mini project. Thanks.

Comments are closed.

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.