Python File Modes (r, w, a, x)


Python allows you to read, write, append, and create files using different modes with the open() function.

open("filename", "mode")

🔹 "r" – Read (Default Mode)

f = open("file.txt", "r")
print(f.read())
f.close()

✅ Opens file for reading only.
❌ Raises error if the file doesn’t exist.


🔹 "w" – Write (Overwrite)

f = open("file.txt", "w")
f.write("Hello, World!")
f.close()

✅ Creates the file if it doesn't exist.
⚠️ Overwrites the file if it exists.


🔹 "a" – Append

f = open("file.txt", "a")
f.write("\nNew line added.")
f.close()

✅ Adds new content to the end of the file.
✅ Keeps existing content untouched.


🔹 "x" – Create

f = open("newfile.txt", "x")
f.write("This file was created.")
f.close()

✅ Creates the file.
❌ Raises error if file already exists.


🔹 "t" – Text Mode (Default)

f = open("file.txt", "rt")  # same as "r"

✅ Used for text files.


🔹 "b" – Binary Mode

f = open("file.jpg", "rb")
data = f.read()
f.close()

✅ Used for binary files like images, PDFs, etc.


🔹 Combine Modes

Mode Description
"rb" Read binary
"wb" Write binary
"ab" Append binary
"rt" Read text (default)
"wt" Write text

Practice Questions

Q1. Write a Python program to open a file in read ("r") mode and print its content.

Q2. Write a Python program to write "Good Morning" to a file using "w" mode (overwrites existing content).

Q3. Write a Python program to append a message to a file using "a" mode without deleting previous content.

Q4. Write a Python program to create a file using "x" mode and add some text (error if file already exists).

Q5. Write a Python program to handle error if a file does not exist in "r" mode using try-except.

Q6. Write a Python program to use "wb" mode to write binary data like b'010101' to a file.

Q7. Write a Python program to open a text file using "rt" mode and read its content.

Q8. Write a Python program to try opening a non-existing file in "x" mode and handle the error.

Q9. Write a Python program to check what happens if "w" mode is used on an existing file (observe overwritten content).

Q10. Write a Python program to read image data using "rb" mode and print the type of the data (should be bytes).


Go Back Top