Python allows you to control file access using different file modes in the open() function. These modes determine whether a file is opened for reading, writing, appending, or binary access.


🔹 File Access Modes in Python

Mode Description
'r' Read (default), raises an error if the file does not exist.
'w' Write, creates a new file or overwrites an existing file.
'a' Append, writes at the end without removing existing content.
'x' Exclusive creation, fails if the file exists.
'b' Binary mode (used with 'r', 'w', 'a', 'x').
't' Text mode (default, used with 'r', 'w', 'a').
'+' Read and write mode ('r+', 'w+', 'a+').

🔹 Controlling File Access with Different Modes

1️⃣ Read Mode ('r')

  • Opens an existing file for reading.
  • Raises an error if the file does not exist.
try:
    file = open("data.txt", "r")
    print(file.read())
    file.close()
except FileNotFoundError:
    print("File not found!")

Use Case: Reading data from configuration files, logs, etc.


2️⃣ Write Mode ('w')

  • Creates a new file if it does not exist.
  • Overwrites the file if it exists.
file = open("data.txt", "w")
file.write("This will overwrite the file.\n")
file.close()

Use Case: Writing new log files, generating reports.


3️⃣ Append Mode ('a')

  • Creates the file if it does not exist.
  • Adds data at the end without removing existing content.
file = open("data.txt", "a")
file.write("New line added at the end.\n")
file.close()

Use Case: Adding log entries, saving user input.


4️⃣ Exclusive Creation Mode ('x')

  • Creates a file but fails if the file already exists.
try:
    file = open("newfile.txt", "x")
    file.write("This is a new file.")
    file.close()
except FileExistsError:
    print("File already exists!")

Use Case: Ensuring that a file is created only once.


🔹 Controlling Binary & Text Mode

1️⃣ Binary Mode ('b')

Used for handling images, videos, and binary files.

file = open("image.jpg", "rb")  # Read in binary mode
data = file.read()
file.close()

Use Case: Processing image files, PDFs, or videos.


2️⃣ Text Mode ('t')

  • Default mode for handling text files.
file = open("data.txt", "rt")  # Equivalent to 'r'
content = file.read()
print(content)
file.close()

Use Case: Reading text documents, logs, and CSV files.


🔹 Read & Write Modes

1️⃣ Read + Write Mode ('r+')

  • Reads and writes to an existing file.
  • Error if the file does not exist.
with open("data.txt", "r+") as file:
    content = file.read()
    file.write("\nAdding more text!")  # Writing after reading
    file.seek(0)
    print(file.read())  # Read updated content

Use Case: Editing configuration files.


2️⃣ Write + Read Mode ('w+')

  • Creates a new file or overwrites an existing file.
with open("data.txt", "w+") as file:
    file.write("Overwritten content.\n")
    file.seek(0)
    print(file.read())  # Reads after writing

Use Case: Creating temporary files.


3️⃣ Append + Read Mode ('a+')

  • Creates the file if it doesn’t exist.
  • Appends data and allows reading.
with open("data.txt", "a+") as file:
    file.write("Appended text.\n")
    file.seek(0)
    print(file.read())  # Reads the updated file

Use Case: Logging system updates.


🔹 Best Practice: Use with open()

Using with open() automatically closes the file after operations.

with open("data.txt", "r") as file:
    content = file.read()
    print(content)

Prevents file corruption and resource leaks.


🔹 Summary

Mode Action
'r' Read (file must exist).
'w' Write (creates/overwrites file).
'a' Append (adds content at the end).
'x' Create (fails if file exists).
'b' Binary mode (use with 'r', 'w', 'a').
't' Text mode (default).
'r+' Read & write (file must exist).
'w+' Write & read (overwrites file).
'a+' Append & read.

Would you like a real-world example, like managing log files? 🚀


Leave a Reply

Your email address will not be published. Required fields are marked *