Member-only story
Python File Modes Explained
2 min readFeb 4, 2025
In Python, file modes specify how a file should be opened and manipulated. These modes determine whether you can read, write, append, or perform other operations on a file. When using the open()
function, you pass the desired mode as a string argument. Here's a breakdown of the different file modes available:
Read for free: https://allwin-raju.medium.com/python-file-modes-explained-7a37760b283d?sk=9df8f46c47ea645ae8529a56908c33a2
Examples of File Modes
1. Read Mode ('r'
)
with open('example.txt', 'r') as file:
content = file.read()
print(content)
- Opens
example.txt
for reading. - Raises a
FileNotFoundError
if the file doesn't exist.
2. Write Mode ('w'
)
with open('example.txt', 'w') as file:
file.write("Hello, World!")
- Opens
example.txt
for writing. - Creates the file if it doesn’t exist.
- Overwrites the file if it exists.
3. Append Mode ('a'
)
with open('example.txt', 'a') as file:
file.write("\nThis is a new line.")
- Opens
example.txt
for appending. - Creates the file if it doesn’t…