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
| Mode | Description |
|---|---|
"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
| Mode | Purpose |
|---|---|
"r" | Read |
"w" | Write |
"a" | Append |
"x" | Create |
"rb" | Read binary |
"wb" | Write binary |