In Python (programming language), file modes determine how a file is opened and used. When using the open() function, you specify a mode to tell Python whether you want to read, write, append, or work with binary files.


πŸ“ Syntax

file = open("filename", "mode")

Example:

file = open("data.txt", "r")

Here:

  • "data.txt" β†’ file name
  • "r" β†’ read mode

πŸ“– Common File Modes

ModeDescription
"r"Read file (default mode)
"w"Write to file (overwrites existing content)
"a"Append data to the end of file
"x"Create a new file
"rb"Read binary file
"wb"Write binary file
"r+"Read and write
"a+"Append and read

1️⃣ Read Mode ("r")

Used to read a file.

Example:

file = open("data.txt", "r")

content = file.read()

print(content)

file.close()

⚠️ Error occurs if the file does not exist.


2️⃣ Write Mode ("w")

Used to write data to a file.

  • Creates file if it does not exist
  • Overwrites existing content

Example:

file = open("data.txt", "w")

file.write("Hello Python")

file.close()

3️⃣ Append Mode ("a")

Adds content to the end of a file without deleting existing data.

Example:

file = open("data.txt", "a")

file.write("\nNew line added")

file.close()

4️⃣ Create Mode ("x")

Creates a new file.

⚠️ Error occurs if file already exists.

Example:

file = open("newfile.txt", "x")

5️⃣ Binary Modes ("rb" and "wb")

Used for binary files like:

  • images
  • videos
  • PDFs

Example:

file = open("image.jpg", "rb")

6️⃣ Read and Write Mode ("r+")

Allows both reading and writing.

Example:

file = open("data.txt", "r+")

print(file.read())

file.write("\nExtra content")

file.close()

7️⃣ Append and Read Mode ("a+")

Allows appending and reading.

Example:

file = open("data.txt", "a+")

file.write("New text")

file.close()

βœ… Using with open() (Recommended)

Best practice for file handling:

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

Advantages:

βœ” Automatically closes file
βœ” Cleaner code
βœ” Safer resource management


πŸ“Œ Example Program

with open("student.txt", "w") as file:
file.write("Name: Rahul\n")
file.write("Course: Python")

🧠 Summary

ModePurpose
"r"Read
"w"Write
"a"Append
"x"Create
"rb"Read binary
"wb"Write binary