HOWTO · Python

How to Redirect Print Output to a File in Python

Learn how to write text and printed output to a file in Python, append content, and choose the right file-writing method.

On this page

To save text to a file in Python, open it with open() and write through the returned file object. Use mode "w" to create or replace a file, or "a" to add content at its end. A with statement closes the file when the block ends.

This example writes a message to report.txt and then displays the saved text:

from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as folder:
    path = Path(folder) / "report.txt"
    with path.open("w", encoding="utf-8") as file:
        file.write("Monthly report\nRevenue: 1200\n")
    print(f"Saved to {path.name}:")
    print(path.read_text(encoding="utf-8"), end="")
Saved to report.txt:
Monthly report
Revenue: 1200

The examples below show when to use write(), print(), standard-output redirection, writelines(), or the pathlib path interface. Most examples use a with statement to close the file automatically; the sys.stdout example restores the previous stream and closes its file explicitly.

Write text with open() and write()

open() chooses how a file is opened; write() is a method on the file object it returns. Mode "w" creates a file or replaces its existing contents. Mode "a" creates the file if needed and adds text at the end. These are file-opening modes, not operations of write().

write() accepts a string and does not add a line break. Include \n where you want a new line. The return value is the number of characters written.

from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as folder:
    path = Path(folder) / "notes.txt"
    with path.open("w", encoding="utf-8") as file:
        file.write("First line\n")
        file.write("Second line\n")
    print(path.read_text(encoding="utf-8"), end="")
First line
Second line

To append, change the mode to "a". For example, with open("notes.txt", "a", encoding="utf-8") as file: file.write("Next entry\n") adds a line after the existing content. The path is resolved relative to the program’s current working directory unless you supply another path.

Use print(..., file=file_object) when you want the familiar formatting behavior of print() but need its output in a file. It converts objects to text, separates multiple values with a space by default, and adds a newline by default. sep and end let you change those choices.

from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as folder:
    path = Path(folder) / "summary.txt"
    with path.open("w", encoding="utf-8") as file:
        print("Count:", 3, file=file)
        print("Ready:", True, file=file)
    print(path.read_text(encoding="utf-8"), end="")
Count: 3
Ready: True

The with block closes the file when printing is finished. Calling close() inside that block is unnecessary; after the block exits, Python closes the file for you.

Redirect standard output with sys.stdout

sys.stdout is the stream used by print() when no file argument is supplied. Assigning a file to sys.stdout redirects standard output for the process, so save and restore the previous stream and close the file. For routine, scoped redirection, prefer contextlib.redirect_stdout() in the next section. See the sys.stdout reference.

import sys
from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as folder:
    path = Path(folder) / "log.txt"
    previous_stdout = sys.stdout
    file = path.open("w", encoding="utf-8")
    try:
        sys.stdout = file
        print("Job complete")
    finally:
        sys.stdout = previous_stdout
        file.close()
    print(path.read_text(encoding="utf-8"), end="")
Job complete

Restoring the original stream in finally ensures later output goes to its prior destination, including when code in the redirected block fails. The outer with manages the temporary directory; the file itself is closed explicitly after restoring sys.stdout.

Temporarily redirect output with contextlib.redirect_stdout()

contextlib.redirect_stdout() temporarily points sys.stdout at a file-like object inside a with block. When the block ends, the previous standard-output stream is restored. The file remains managed by its own with statement.

import contextlib
from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as folder:
    path = Path(folder) / "output.txt"
    with path.open("w", encoding="utf-8") as file:
        with contextlib.redirect_stdout(file):
            print("Build finished")
    print(path.read_text(encoding="utf-8"), end="")
Build finished

This approach captures print() calls and other writes to standard output made inside the context. It does not redirect standard error (sys.stderr).

Write a sequence with writelines()

writelines() writes each string from an iterable to the file in order. It does not insert line breaks, so include \n in the strings when the file should contain separate lines.

from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as folder:
    path = Path(folder) / "items.txt"
    lines = ["apples\n", "pears\n", "plums\n"]
    with path.open("w", encoding="utf-8") as file:
        file.writelines(lines)
    print(path.read_text(encoding="utf-8"), end="")
apples
pears
plums

The elements must be strings for a text file. If line breaks are not wanted, leave \n out of each string.

Open and write files with pathlib

pathlib provides objects for building and working with filesystem paths. It does not replace file objects: use Path.open() to get one, then call its write() method. This is useful when the path is assembled from folders or other path components.

from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as folder:
    path = Path(folder) / "archive" / "entry.txt"
    path.parent.mkdir()
    with path.open("w", encoding="utf-8") as file:
        file.write("Stored with pathlib.\n")
    print(path.read_text(encoding="utf-8"), end="")
Stored with pathlib.

Use Path.write_text() for a concise one-step text write when you do not need to manage a file object directly. For repeated writes or methods such as writelines(), Path.open() gives you the file object to work with.

For the reverse task, see how to read a file into a string in Python.