HOWTO · Python

How to Use the cat Command in Python

Learn how to use the cat command in Python with this comprehensive guide. Explore methods like using the open function, pathlib module, and subprocess to read and manipulate files efficiently. Perfect for both beginners and experienced programmers looking to enhance their file handling skills in Python.

On this page

Python does not include a cat command. To display a file from Python, use open() or pathlib; invoke the external cat utility with subprocess only when you specifically need that Unix command. The Python approaches work across platforms and avoid launching another process.

Use open() to read and display a file

Use open() as a context manager to read a text file. The example creates its own input file so you can run it as written. It specifies UTF-8 encoding, and the with block closes the file after reading.

Run this example:

from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as directory:
    file_path = Path(directory) / "example.txt"
    file_path.write_text("First line.\nSecond line.\n", encoding="utf-8")

    with open(file_path, "r", encoding="utf-8") as file:
        print(file.read(), end="")

For a large file, avoid reading all of its contents into one string. Iterate over the file instead, for example with for line in file:, and process each line as it is read.

Use pathlib for a concise file read

pathlib.Path.read_text() is a concise alternative when the whole text file fits comfortably in memory. Like the previous example, this one creates its input and names the encoding explicitly.

from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as directory:
    file_path = Path(directory) / "example.txt"
    file_path.write_text("First line.\nSecond line.\n", encoding="utf-8")
    print(file_path.read_text(encoding="utf-8"), end="")

Both approaches decode bytes into text. Choose an encoding that matches the file; UTF-8 is common, but files from other systems may use a different encoding. For large files, use open() and process lines incrementally rather than loading the whole file.

Run cat with subprocess when you need the shell command

If a workflow specifically requires the Unix cat utility, call it with subprocess.run() and pass the program and file path as separate list items. This avoids shell parsing of the path. The example checks whether the utility is installed, captures its standard output and error, and reports a missing command without failing.

from pathlib import Path
import shutil
import subprocess
from tempfile import TemporaryDirectory

with TemporaryDirectory() as directory:
    file_path = Path(directory) / "example.txt"
    file_path.write_text("First line.\nSecond line.\n", encoding="utf-8")

    cat_program = shutil.which("cat")
    if cat_program is None:
        print("cat is not available on this system.")
    else:
        result = subprocess.run(
            [cat_program, str(file_path)],
            capture_output=True,
            text=True,
            encoding="utf-8",
            check=False,
        )
        if result.returncode == 0:
            print(result.stdout, end="")
        else:
            print(result.stderr, end="")

This invokes an external program; it does not make cat a Python command or a file-reading API. The Unix utility is generally not installed on Windows, so prefer Python’s built-in file APIs for portable scripts. When invoking any external program, keep arguments separate and avoid constructing a shell command from untrusted input.

Conclusion

Use open() for line-by-line processing or a direct whole-file read, and use pathlib when its path-based read_text() method makes the code clearer. Run cat through subprocess only when the external Unix utility itself is required. Whole-file methods use memory in proportion to the file size; process large files incrementally.

FAQ

  1. What is the cat command?
    It is a Unix utility that displays or concatenates files. It is not built into Python.

  2. Can I run cat on Windows?
    Usually it is not available by default. Python’s open() and pathlib provide portable ways to read files; Windows also has separate shell commands, but they are not the Unix utility.

  3. Should I use subprocess or open() to read a file?
    Use open() or pathlib for ordinary file access. Use subprocess when you need to run cat or another external program.

  4. Can these methods handle large files?
    Reading a whole file with read() or read_text() stores its contents in memory. For large files, use open() and process one line at a time.