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! โจ