When dealing with text or binary files in Python, use the built-in function open(). This function creates a file object by specifying a “mode” such as reading, writing, or appending.
Also, in file operations, you must close the file (release resources) after the process is finished.
This article explains the main modes of the open() function and how to use the with statement to handle files safely and concisely.
List of File Opening Modes
The second argument of the open() function is a string specifying the “mode” in which to open the file.
The default is ‘rt’ (read in text mode), but you can combine the following characters depending on your needs.
| Character | Meaning | Details |
r | Read | Reads an existing file. If the file does not exist, an error (FileNotFoundError) occurs. This is the default mode. |
w | Write | Writes a new file. If the file already exists, all contents are erased (overwritten). If it doesn’t exist, it is created. |
a | Append | Adds data to the end of the file. If the file doesn’t exist, it is created. Existing data is preserved. |
r+ | Read/Write | Performs both reading and writing. The file must exist. The file pointer is placed at the beginning. |
a+ | Read/Write (Append) | Performs both reading and writing. If the file doesn’t exist, it is created. The file pointer is placed at the end (for appending). |
b | Binary Mode | Used when handling image or audio data (e.g., rb, wb). |
t | Text Mode | Used when handling string data. Usually omitted as it is the default (e.g., rt is the same as r). |
Safe File Operations with the with Statement
After opening a file (open), you must close it (close). However, if an error occurs during processing, close() might not be executed, risking leaving the file open.
In Python, by using the with statement, the file is automatically closed when the process inside the block ends (whether normally or due to an error).
Recommended Writing Style:
# Writing to a file (Create new or overwrite)
# Specify 'w' mode
file_path = "project_log.txt"
with open(file_path, "w", encoding="utf-8") as log_file:
log_file.write("2025-12-01: Project Started\n")
log_file.write("2025-12-02: Initial Setup Complete\n")
print(f"Wrote to {file_path}.")
Result:
A file named project_log.txt is created, and two lines of text are written. log_file.close() is automatically called when exiting the with block.
Reading a File
Here is an example of reading the created file.
# Reading a file
# Specify 'r' mode (Optional)
with open(file_path, "r", encoding="utf-8") as file_handle:
# Read all content as a string with read()
content = file_handle.read()
print("--- File Content ---")
print(content)
Output:
--- File Content ---
2025-12-01: Project Started
2025-12-02: Initial Setup Complete
Specifying Encoding (Character Code)
When dealing with text files, relying on the OS’s default encoding can cause garbled characters between Windows (cp932) and macOS/Linux (utf-8).
Therefore, it is strongly recommended to explicitly specify encoding=”utf-8″ in the open() function.
Checking the System’s Default Encoding
You can check what encoding is used when encoding is omitted in the current environment using the standard library locale.
import locale
# Get the system's preferred encoding
default_encoding = locale.getpreferredencoding(False)
print(f"Default encoding in this environment: {default_encoding}")
Output (Windows Example):
Default encoding in this environment: cp932
Output (macOS/Linux Example):
Default encoding in this environment: UTF-8
To avoid troubles caused by this difference, it is important to make it a habit to always specify the encoding argument when writing cross-platform code.
Summary
- Use the
open()function to open files. - Select the appropriate mode:
r(read),w(overwrite), ora(append). - Using the
with open(...) as f:syntax prevents forgetting toclose()and handles files safely. - Explicitly specifying
encoding="utf-8"is recommended to prevent garbled characters.
