🚀 Supercharge your YouTube channel's growth with AI.
Try YTGrowAI FreeHow to Open Files in Python

To read information saved in a file, your Python program first needs to open it. Python’s built-in open() function opens a path and returns a file object your program can use to read or write data.
This article shows how to give open() the right path and read text inside a with block.
TL;DR
Open a path in read mode with open() inside a with block, then read from the returned file object.
- Use a relative path from the process working directory or pass an absolute path.
- Set the text encoding when you know how the file was saved.
- Choose r to read, w to replace, a to append, or x to create without replacing an existing file.
What Is open() in Python?
open() is a built-in function that opens a path and returns a file object, the stream your program uses to read or write data.
The first argument is a path. A relative path is resolved from the process’s current working directory, which can differ from the directory containing your script. An absolute path names the location from the filesystem root.
You can pass a string path or a pathlib.Path object. I use a Path object in the read example because the successful command shows that open() accepts it directly.
The mode describes the operation. If you omit it, open() uses r for reading text. The returned object keeps a cursor, so each read begins where the preceding operation stopped.
Text mode decodes bytes into strings with an encoding. Binary mode returns bytes without text decoding, which suits images and other non-text files.
| Mode | Value | Use |
|---|---|---|
| Text | str | Text files |
| Binary | bytes | Images and other binary data |
How to Open and Read a File in Python
Find the file, choose a read mode and encoding, then use the file object inside a context manager.
Step 1: Point to the file you want to read
Check the filename and its extension before changing the program. A spelling difference or hidden extra extension means the path names a different file.
Check where the process starts as well. The pwd command prints the working directory in a Linux or macOS terminal, and pathlib.Path.cwd() returns that location from Python.
Choose a relative path when the command starts in the directory containing the data. Use an absolute path when the file lives elsewhere. For a data file shipped beside a saved script, build a path from pathlib.Path(__file__).parent and add the filename.
| Path | Example | Use when |
|---|---|---|
| Relative | notes.txt | Starting in the data directory |
| Absolute | /home/sam/data/notes.txt | Starting elsewhere |
| Script-based | Path(__file__).parent / “notes.txt” | Data ships with the script |
Step 2: Read text inside a with block
The demo script creates notes.txt in its current working directory with First line and Second line, then opens that Path as UTF-8 text. Change the filename before running it if you need to keep an existing notes.txt.
from pathlib import Path
path = Path("notes.txt")
path.write_text("First line\nSecond line\n", encoding="utf-8")
with open(path, "r", encoding="utf-8") as file:
for line in file:
print(line, end="")
print(f"Closed after with: {file.closed}")
I ran python3.14 open_file_read_demo.py. It printed the two saved lines and showed that the file was closed after the with block.
First line Second line Closed after with: True

The with statement closes the file when execution leaves its indented block, including when an exception interrupts that block.
read() without a size returns all remaining text as one string, so choose it when the whole file fits in memory. The read example iterates over the file object instead, which avoids collecting every line into a list before processing.
readline() returns one line and keeps its newline when one is present. readlines() returns a list of line strings, which can use as much memory as the full text. Direct iteration suits a log or other file whose size is not known in advance.
For a small text file that you want as one string, pathlib.Path.read_text() reads and closes it in one call. Choose open() when the code needs a file object for line-by-line reading, a particular mode, or several operations.
Step 3: Select a mode before writing
Choose the mode from the action you intend to take, because opening a file in write mode can erase its existing contents before any write call.
| Mode | Existing file | Missing file |
|---|---|---|
| r | Read | Error |
| w | Truncate and write | Create |
| a | Append | Create |
| x | FileExistsError | Create exclusively |
| r+ | Read and write without truncation | Error |
| w+ | Truncate, then read and write | Create |
| a+ | Read and append | Create |
Add b to a mode for binary data, such as rb or wb. The plus sign allows both reading and writing, but does not make the modes interchangeable. In text mode, set encoding to the file’s actual encoding when it is known.
I compared r+ with a in python3.14 open_file_modes_demo.py. The r+ write replaced the character at the current position, while a added its character at the end.
from pathlib import Path
path = Path("mode-notes.txt")
path.write_text("Hello", encoding="utf-8")
with open(path, "r+", encoding="utf-8") as file:
file.write("Y")
file.seek(0)
print("r+:", file.read())
with open(path, "a", encoding="utf-8") as file:
file.write("!")
print("a:", path.read_text(encoding="utf-8"))
r+: Yello a: Yello!

A call to write() adds only the characters in its argument and does not add a line break. In the comparison, the appended exclamation mark joined Yello on the same line. Include a newline character when each log record should start on a new line.
File Errors and Mode Choices
A failed open usually points to a path that does not resolve, an operation the selected mode does not allow, or text bytes that do not match the chosen encoding.
I ran python3.14 open_file_missing_demo.py with missing-notes.txt absent. The program printed this FileNotFoundError message.
from pathlib import Path
path = Path("missing-notes.txt")
try:
with open(path, encoding="utf-8") as file:
print(file.read())
except FileNotFoundError as error:
print(f"{type(error).__name__}: {error}")
FileNotFoundError: [Errno 2] No such file or directory: 'missing-notes.txt'

Compare the reported filename with the file you meant to open. Check the current directory before changing a mode.
| Symptom | Check | Action |
|---|---|---|
| FileNotFoundError | Name, extension, path | Verify the path |
| PermissionError | File and directory access | Check permissions |
| IsADirectoryError | Path names a directory | Select a file within it |
| UnicodeDecodeError | Encoding mismatch | Use the source encoding |
| Old text disappears | w truncates on open | Choose a or x as intended |
On Windows, a backslash followed by U in a normal string starts a Unicode escape. Use a raw string or build the path from pathlib.Path components. Opening with w truncates an existing file, so choose it only when replacement is intended.
Conclusion
For the API details, see Python’s open() reference, its file input and output tutorial, and the csv module documentation. For reading methods, continue with Python Read File: Three Ways You Must Know or How to Read and Parse a Text File in Python.
FAQ
These answers cover file types and closure checks that take a different operation from opening a file.
How do I open a CSV file in Python?
Use open(path, newline=”) and pass the text stream to csv.reader. It parses quoted fields and embedded line breaks.
How can I tell whether a file is closed?
Check the file object’s closed attribute. It is True after the with block exits, as the read example above prints.
How do I open a Python file in a terminal?
To run a Python script, start the interpreter with the script filename from its directory, such as python3.14 open_file_read_demo.py. The open() function reads a file as data. It does not execute Python source code.


