Python
print function
file handling
redirect output
coding tutorial

How to redirect 'print' output to a file?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

In Python, print() writes to standard output by default, which usually means the terminal. Redirecting that output to a file is useful for simple reports, quick logging, and capturing the output of code you do not want to rewrite immediately.

Using the file Parameter on print()

The simplest approach is to open a file and pass that file handle to the file argument of print(). This keeps the redirection local to the line where you need it.

python
1with open("report.txt", "w", encoding="utf-8") as handle:
2    print("Daily summary", file=handle)
3    print("processed=42", file=handle)
4    print("failed=0", file=handle)

Using a with block is the important part. It guarantees the file is closed even if an exception occurs. For one-off output, this is usually better than manually opening and closing the file.

The file mode controls behavior:

  • '"w" overwrites the file.'
  • '"a" appends to the end.'
  • '"x" creates a new file and fails if it already exists.'

If you need a blank file for each run, use "w". If you are adding new entries to an existing log, use "a".

Redirecting a Larger Block of Output

If a function contains many print() calls, passing file=... to each one can get noisy. In that case, temporarily redirect standard output.

python
1from contextlib import redirect_stdout
2
3
4def show_summary():
5    print("Build started")
6    print("Step 1: lint")
7    print("Step 2: tests")
8    print("Build finished")
9
10
11with open("build.log", "w", encoding="utf-8") as handle:
12    with redirect_stdout(handle):
13        show_summary()

Inside the redirect_stdout block, normal print() calls go to the file instead of the console. This is useful for legacy code, notebooks converted to scripts, or helper functions that already print directly.

Handling Encoding, Buffering, and Flushing

Text files should usually be opened with an explicit encoding. utf-8 is the safest default for modern programs because it handles non-ASCII text consistently across environments.

If you want output written immediately, either pass flush=True to print() or call handle.flush().

python
with open("stream.log", "a", encoding="utf-8") as handle:
    for step in range(3):
        print(f"step={step}", file=handle, flush=True)

Immediate flushing is useful when another process is reading the file as it is written, or when a long-running job may terminate unexpectedly and you want the file to contain the latest progress.

When print() Is Not the Best Tool

Redirecting print() is fine for quick scripts, but applications that need timestamps, severity levels, or rotating files should usually use the logging module instead. print() is just text output. It does not know whether a line is informational, a warning, or a failure.

Still, for simple tasks, print() is perfectly reasonable:

python
1records = ["alice", "bob", "carol"]
2
3with open("users.txt", "w", encoding="utf-8") as handle:
4    for name in records:
5        print(name, file=handle)

This stays readable, requires no extra framework, and is often enough for scripts that generate a small text artifact.

Common Pitfalls

One frequent mistake is forgetting the file mode. Opening with "w" will replace existing content, which surprises people who expected appending behavior.

Another issue is leaving out the with block and forgetting to close the file. The script may appear to work, but buffered output can remain unwritten until the program exits.

It is also easy to confuse redirecting print() with redirecting all output. print() uses standard output, but tracebacks and many warnings go to standard error. If you need both streams captured, you must handle them separately.

Summary

  • Pass file=handle to print() for simple, explicit redirection.
  • Use redirect_stdout() when you want to capture many existing print() calls at once.
  • Choose the correct file mode so you do not accidentally overwrite output you meant to keep.
  • Open text files with encoding="utf-8" for predictable behavior.
  • For structured application logging, prefer the logging module over heavy use of print().

Course illustration
Course illustration

All Rights Reserved.