File modes define how a file should be opened — whether for reading, writing, appending, or both.
When using the open() function, the second parameter specifies the mode.
file = open("example.txt", "r")
COMMON FILE MODES
1. Read Mode ("r")
- Opens a file for reading
- Default mode
- Gives error if file does not exist
with open("example.txt", "r") as file:
content = file.read()
2. Write Mode ("w")
- Opens a file for writing
- Creates file if it does not exist
- Overwrites file if it already exists
with open("example.txt", "w") as file:
file.write("Hello World")
3. Append Mode ("a")
- Opens file for adding content
- Creates file if it does not exist
- Does NOT delete existing content
with open("example.txt", "a") as file:
file.write("New Line\n")
4. Exclusive Creation Mode ("x")
- Creates a new file
- Gives error if file already exists
with open("newfile.txt", "x") as file:
file.write("New File Created")
READ & WRITE MODES
5. Read and Write ("r+")
- Opens file for reading and writing
- File must exist
- Does NOT overwrite automatically
with open("example.txt", "r+") as file:
file.write("Updated")
6. Write and Read ("w+")
- Opens file for reading and writing
- Overwrites existing content
- Creates file if it does not exist
with open("example.txt", "w+") as file:
file.write("Fresh Start")
7. Append and Read ("a+")
- Opens file for reading and appending
- Does NOT overwrite
- Creates file if it does not exist
with open("example.txt", "a+") as file:
file.write("Extra Line")
BINARY MODES
Add "b" to work with binary files (images, PDFs, etc.)
"rb"→ Read binary"wb"→ Write binary"ab"→ Append binary
Example:
with open("image.jpg", "rb") as file:
data = file.read()
TEXT MODE (Default)
Add "t" for text mode (optional because it is default)
"rt"→ Read text"wt"→ Write text
SUMMARY TABLE
| Mode | Purpose | File Exists? |
|---|---|---|
| r | Read | Must exist |
| w | Write | Overwrites |
| a | Append | Keeps content |
| x | Create | Error if exists |
| r+ | Read & Write | Must exist |
| w+ | Write & Read | Overwrites |
| a+ | Append & Read | Keeps content |
BEST PRACTICE
Always use the with statement:
with open("example.txt", "r") as file:
data = file.read()
This ensures the file closes automatically.
Understanding file modes is essential for handling data safely and effectively in Python applications.