Pass an open writable file object to the file= keyword argument of print("...", file=f) inside a with open(path, "w", encoding="utf-8") as f: context manager—or temporarily reassign sys.stdout using contextlib.redirect_stdout(f) when capturing print() output from existing functions or third-party code you cannot modify.
Basic Example
from contextlib import redirect_stdout
# 1. Recommended for explicit prints: Pass `file=f` directly to print()
with open("output.txt", "w", encoding="utf-8") as f:
print("Header line", file=f)
print("Values:", 10, 20, 30, sep=", ", file=f)
# 2. Redirect all standard output inside a block using contextlib.redirect_stdout()
def legacy_report() -> None:
print("Generated report line 1")
print("Generated report line 2")
with open("report.txt", "w", encoding="utf-8") as f:
with redirect_stdout(f):
legacy_report() # Every print() inside this block writes straight to report.txt
# Outside the `with` block, print() automatically goes back to the console
print("Back to terminal output!")
Key Details & Edge Cases
"w"(overwrite) vs."a"(append) file modes:- Opening with
"w"truncates and replaces the file every timeopen()runs. Use"a"(open("output.txt", "a", encoding="utf-8")) to preserve existing file contents and append new lines at the end.
- Opening with
- Always pass
encoding="utf-8"and use awithstatement:- Omitting
encoding="utf-8"uses the OS locale encoding (e.g.,cp1252on Windows), which raisesUnicodeEncodeErrorif your printed strings contain emojis or non-ASCII characters. - Using
with open(...) as f:ensures the buffer is flushed and the file descriptor is closed automatically even if an exception occurs mid-write.
- Omitting
- Forcing immediate writes during long-running scripts (
flush=True):- File streams buffer output in memory before flushing to disk. If you are tailing a log file (
tail -f output.txt) in real time, passflush=True(print("Step complete", file=f, flush=True)).
- File streams buffer output in memory before flushing to disk. If you are tailing a log file (
print(..., file=f)vs.f.write(...):print()automatically converts non-string arguments (int,list,dict) viastr(), joins multiple positional arguments withsep=" ", and appends a trailing newline (end="\n").f.write(text)requires a singlestrargument (raisingTypeErroron integers orNone) and does not append\nautomatically, makingf.write()slightly faster in tight loops when you already hold pre-formatted strings.
- What
redirect_stdoutdoes NOT capture:contextlib.redirect_stdout(f)redirects Python-levelsys.stdoutonly. It does not capturesys.stderr(usecontextlib.redirect_(f)for errors) or output written directly to OS file descriptors1/2by C extensions orsubprocess.run()(passstdout=fdirectly tosubprocess.run(..., stdout=f)instead).
- Redirecting from the command line without editing Python code: If you want all terminal output of an entire script saved to a file, shell redirection (
python script.py > output.txt 2>&1) captures bothstdoutandstderrexternally without modifying your script.
Comparison of Output-to-File Redirection Methods in Python
| Method | Syntax | Modifies Global sys.stdout? |
Auto-Formats Non-Strings & \n? |
Best Used When |
|---|---|---|---|---|
print(..., file=f) |
print("msg", x, file=f) |
No (explicit per call) | Yes (sep and end="\n") |
Writing formatted lines directly to a specific file in your own code. |
contextlib.redirect_stdout(f) |
with redirect_stdout(f): fn() |
Temporarily inside with block |
Yes (captures all print()) |
Capturing print() output from helper functions or third-party libraries safely. |
f.write(s) / f.writelines() |
f.write(f"{line}\n") |
No | No (str only, no auto \n) |
High-throughput string writing where manual formatting is already done. |
Manual sys.stdout = f (Avoid) |
sys.stdout = f |
Yes (risks broken state on error) | Yes | Avoid—prefer contextlib.redirect_stdout(f) so sys.stdout is always restored. |
Shell Redirection () |
python app.py > out.txt |
Captures OS stdout FD | N/A | Saving the entire stdout stream of an unmodified CLI script externally. |
You must log in or register to comment.
