Ah, files! They’re everywhere—logs, reports, configurations, and even those secret recipes we stash in .txt files. But have you ever wondered how Python decides whether to read, write, or append to a file? That’s where file access modes come into play!
So, let’s slice and dice (not literally! 😆) through Python’s file access modes and understand when to use what.
Slicing and Dicing is written here by the way – https://brontowise.com/2025/04/06/slicing-and-dicing-in-python-brontowise/
1. Opening a File in Python: The Basics
Before we dive into the different modes, let’s quickly see how we open files in Python:
file = open("example.txt", "mode") # 'mode' decides what we do with the file
The mode argument determines if we’re reading, writing, or appending to the file.
2. The 7 File Access Modes in Python 🚀
| Mode | Meaning | Behavior |
|---|---|---|
'r' | Read | Opens an existing file for reading (default mode) |
'w' | Write | Creates a new file (or overwrites if it exists) |
'a' | Append | Opens a file to add content at the end |
'r+' | Read & Write | Opens a file for both reading and writing |
'w+' | Write & Read | Creates (or overwrites) a file for both writing & reading |
'a+' | Append & Read | Opens a file for both appending & reading |
'x' | Exclusive | Creates a new file; fails if it exists |
Now, let’s explore these modes one by one! 🧐
3. Read Mode ('r'): Just Looking, No Changes! 👀
This mode is like a museum visit—you can look, but you can’t touch!
file = open("data.txt", "r")
content = file.read() # Reads the entire file
file.close()
🔹 If the file doesn’t exist? Python throws an error: FileNotFoundError.
4. Write Mode ('w'): Caution! Overwrites Everything ⚠️
This mode creates a new file or wipes out an existing one.
file = open("data.txt", "w")
file.write("This will replace everything in the file.")
file.close()
🔹 Warning: If data.txt exists, its previous content is gone forever! 😱
5. Append Mode ('a'): Adding More Without Deleting
If you don’t want to lose existing data and just want to add to it, use 'a'.
file = open("data.txt", "a")
file.write("\nNew line added!")
file.close()
🔹 Great for: Logging systems, chat histories, or continuous updates! 📜
6. Read & Write ('r+'): Best of Both Worlds
Want to read and write at the same time? 'r+' lets you do both!
file = open("data.txt", "r+")
print(file.read()) # Read existing content
file.write("\nAppending new text!") # Write new data
file.close()
🔹 If the file doesn’t exist? Boom! FileNotFoundError.
7. Write & Read ('w+'): Be Careful! Overwrites Everything 😬
Just like 'w', this clears the file but allows both reading and writing.
file = open("data.txt", "w+")
file.write("New content!")
file.seek(0) # Move back to the beginning
print(file.read()) # Read what we just wrote
file.close()
🔹 File doesn’t exist? No worries, Python creates one.
8. Append & Read ('a+'): Appending a File
With 'a+', you can read and append at the same time.
file = open("data.txt", "a+")
file.write("\nAdding more text!")
file.seek(0) # Move back to read
print(file.read()) # Read the file
file.close()
🔹 File doesn’t exist? No problem! Python creates it.
9. Exclusive Mode ('x'): Avoid Accidental Overwrites 🚫
If you want to create a file but fail if it already exists, use 'x'.
file = open("new_file.txt", "x")
file.write("This file is new!")
file.close()
🔹 If the file exists? Boom! FileExistsError.
10. Bonus: Working with Binary Files (b Mode)
Sometimes, we deal with images, PDFs, or audio files. In such cases, we use binary mode (b):
file = open("image.jpg", "rb") # Read in binary mode
data = file.read()
file.close()
🔹 Combine with other modes:
'wb'→ Write binary'ab'→ Append binary'rb+'→ Read & write binary
Final Thoughts 🎯
Understanding file access modes helps prevent accidental overwrites, improves efficiency, and ensures you’re using Python correctly.
🚀 Now it’s your turn! Try these modes in your projects and comment below—what’s your favorite file access mode and why? 👇
✨ Stay tuned for more Python tricks at BrontoWise! ✨