File Modes in Python (r, w, a, rb, wb)

 

Understanding File Modes 

When working with files in Python, you must specify a mode—this tells Python what you want to do with the file.

File Mode Options 

Mode Description
'r' Read mode (default) - opens file for reading, error if file doesn’t exist
'w' Write mode - creates new file or overwrites existing one
'a' Append mode - adds new content to an existing file without overwriting
'rb' Read binary - reads file in binary mode (useful for images, videos, etc.)
'wb' Write binary - writes file in binary mode

Read Mode ('r'

with open("example.txt", "r") as file:
    content = file.read()
    print(content)  # Reads entire file

Error if file does not exist!

Write Mode ('w')

with open("example.txt", "w") as file:
    file.write("Hello, Python world!\n")

Warning: Overwrites existing content!

Append Mode ('a'

with open("example.txt", "a") as file:
    file.write("Appending this line!\n")

Does not erase existing content! 

Read Binary Mode ('rb')

Used for non-text files like images, videos, and audio.

with open("image.png", "rb") as file:
    binary_data = file.read()

Write Binary Mode ('wb')

Used to write binary files like images or audio.

with open("new_image.png", "wb") as file:
    file.write(binary_data)

Summary

Mode Purpose
'r' Read file (default)
'w' Write new file (overwrite)
'a' Append to existing file
'rb' Read binary file
'wb' Write binary file

Now you understand how file modes work in Python

 

Post a Comment

0 Comments