File modes are fundamental to working with files in Python. They determine how a file can be opened, read from, written to, and more.
In this article, we’ll dive into the world of file modes, exploring their types and when to use each one.
Understanding File Modes
File modes specify the purpose and access permissions of a file when it is opened. Here are the most common file modes in Python:
- ‘r’ (Read mode): Opens a file for reading. It raises an error if the file does not exist.
with open('example.txt', 'r') as file:
data = file.read()
print(data)
- ‘w’ (Write mode): Opens a file for writing. If the file exists, its contents are overwritten. If the file does not exist, a new file is created.
with open('example.txt', 'w') as file:
file.write('Hello, World!')
- ‘a’ (Append mode): Opens a file for appending. New data is written to the end of the file. If the file does not exist, a new file is created.
with open('example.txt', 'a') as file:
file.write('\nAppending new content!')