In Python, File Modes define the specific permissions and actions allowed when opening a connection to a file. Choosing the correct mode is critical because it determines whether you can read data, write new data, or if you will accidentally delete existing content.
When you use the open() function, the second argument is the Mode String. It tells the operating system's file system how to handle the file pointer:
Where to start: At the beginning or the end of the file?
Permission: Read-only, Write-only, or both?
File Type: Text (t) or Binary (b)?
Read (r): The file pointer is placed at the beginning. If the file doesn't exist, Python throws a FileNotFoundError.
Write (w): Creates a new file. If the file already exists, it truncates (wipes out) everything inside before writing.
Append (a): The file pointer is at the end. If the file exists, new data is added after the current content.
Create (x): Exclusive creation. It fails if the file already exists (preventing accidental overwrites).
| Mode | Description | Pointer Position | Exists? | No File? |
| r | Read Only | Start | OK | Error |
| w | Write Only | Start | Overwrites | Creates |
| a | Append Only | End | OK | Creates |
| r+ | Read & Write | Start | OK | Error |
| w+ | Write & Read | Start | Overwrites | Creates |
| a+ | Append & Read | End | OK | Creates |
| rb / wb | Binary Modes | Start | N/A | Varies |
The + modes are used when you need to perform both reading and writing on the same file object.
# 'r+' allows reading and writing without wiping the file with open("data.txt", "w") as f: f.write("Original Content") with open("data.txt", "r+") as file: content = file.read() # Reads the original print(f"Read: {content}") file.write("\nNew Update") # Adds at the current pointer position
Use this when it is critical that you don't overwrite an existing file (like generating a unique report).
try: with open("secure_report.txt", "x") as file: file.write("Confidential Data") except FileExistsError: print("Error: This file already exists! Choose a different name.")
Used for non-text files like images, PDFs, or compiled data. Note that you must write "bytes" objects (b'').
# Copying an image (binary read and binary write) with open("logo.png", "rb") as source: img_data = source.read() with open("logo_copy.png", "wb") as destination: destination.write(img_data)
Use r for simple data extraction.
Use w for fresh logs or saving a new document.
Use a for continuous logs or chat histories.
Use b suffix for anything that isn't a .txt file.
Copyright ©2025. All Rights Reserved Emblab THE RAVE INNOVATION