When you open a file in Python, you need to tell it how you intend to use that file. This is done using 'file modes'. These modes dictate whether you'll be reading data, writing data, appending data, or a combination, and also whether the file should be treated as text or binary. Let's explore the most common file modes you'll encounter.
The default mode if you don't specify one is 'r' (read). This means you can only read from the file. If the file doesn't exist, Python will raise a FileNotFoundError. This is the safest mode for simply viewing or processing existing file content.
with open('my_document.txt', 'r') as f:
content = f.read()
print(content)The 'w' mode is for writing. If the file exists, its contents will be erased and the file will be empty before new data is written. If the file does not exist, it will be created. Be cautious with this mode, as you can easily overwrite important data.
with open('my_new_file.txt', 'w') as f:
f.write('This is the first line.\n')
f.write('This is the second line.')The 'a' mode is for appending. This mode opens a file for writing, but new data is added to the end of the file. If the file doesn't exist, it will be created. This is useful when you want to add information to an existing log or data file without losing previous entries.
with open('log_file.txt', 'a') as f:
f.write('New log entry added.\n')Sometimes, you might want to read from and write to the same file. The 'r+' mode opens a file for both reading and writing. The file pointer is placed at the beginning of the file. Existing content is not erased. You'll need to be careful about where you are in the file when performing both read and write operations.
with open('data.txt', 'r+') as f:
content = f.read()
f.seek(0) # Move pointer to the beginning
f.write('New header\n')
f.write(content) # Write the original content after the headerSimilarly, 'w+' opens a file for reading and writing. However, unlike 'r+', it truncates (erases) the file if it exists. If the file does not exist, it is created. This is useful for creating a file that you will immediately populate with new data and then might need to read from.
with open('temp_data.txt', 'w+') as f:
f.write('Initial data.\n')
f.seek(0)
print('Content:', f.read())The 'a+' mode opens a file for appending and reading. The file pointer is at the end of the file for writing, but you can move it to read from any part of the file. New data will be appended to the end. This is ideal for log files where you want to append new entries and occasionally review the entire log.
with open('activity.log', 'a+') as f:
f.write('User logged in.\n')
f.seek(0) # Move pointer to beginning to read
print('Log content:\n', f.read())In addition to these, Python also supports binary modes. You append 'b' to any of the text modes to indicate that you are working with a binary file (like images, audio, or executable files). For example, 'rb' for reading binary, 'wb' for writing binary, and 'ab' for appending binary. You'll typically use the bytes data type when working with binary files.
with open('image.jpg', 'rb') as f:
binary_data = f.read()
with open('new_image.jpg', 'wb') as f:
f.write(binary_data)Here's a summary of the main file modes:
graph TD;
A[File Modes] --> B(r: Read - default);
A --> C(w: Write - truncates);
A --> D(a: Append);
A --> E(r+: Read and Write);
A --> F(w+: Write and Read - truncates);
A --> G(a+: Append and Read);
A --> H(b: Binary mode - e.g., rb, wb);
C --> C1{File is cleared if exists};
Understanding these modes is crucial for correctly interacting with files, preventing data loss, and ensuring your programs behave as expected. Always remember to close your files properly, which the with statement conveniently handles for you.