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 header