Practice with Read/Write Modes and Choosing the Right Mode
Python also provides modes that allow both reading and writing within the same open()
context. These offer more flexibility but require careful handling of the file pointer.
- Read and Write (
'r+'
): Opens an existing file for both reading and writing. The pointer starts at the beginning. Writing will overwrite existing content from the pointer's position.
- Write and Read (
'w+'
): Opens a file for writing and reading. It truncates the file if it exists or creates it if not. The pointer starts at the beginning.
- Append and Read (
'a+'
): Opens a file for appending (writing at the end) and reading. It creates the file if it doesn't exist. The pointer starts at the end for writing, but you can move it (e.g., using file.seek(0)
) to read from the beginning.
Let's demonstrate 'r+'
. We'll use the my_reading_file.txt
created in Step 1. We will open it, read the content, then move the pointer back to the start and overwrite the beginning of the file.
Create a Python file named rplus_example.py
in /home/labex/project
. Add this code:
try:
## Open the file in read and write mode ('r+')
## The file must exist for this mode.
with open('/home/labex/project/my_reading_file.txt', 'r+') as file:
## Read the initial content
initial_content = file.read()
print("Initial file content:")
print(initial_content)
## Move the file pointer back to the beginning
print("\nMoving pointer to the beginning using file.seek(0).")
file.seek(0)
## Write new content at the beginning (overwriting existing content)
print("Writing new content...")
file.write("Prepended line 1.\n")
file.write("Prepended line 2.\n")
## If the new content is shorter than what was overwritten,
## the rest of the original content might remain unless truncated.
## We can use file.truncate() after writing to remove any trailing old data.
print("Truncating file to the current position to remove old trailing data.")
file.truncate()
print("\nContent written and file truncated.")
except FileNotFoundError:
print("Error: The file was not found. 'r+' requires the file to exist.")
except Exception as e:
print(f"An error occurred: {e}")
print("\nFinished with r+ mode example.")
This script opens the file in 'r+'
, reads, seeks back to the beginning (file.seek(0)
), writes new lines (overwriting), and then uses file.truncate()
to remove any leftover original content that might exist beyond the newly written text.
Save rplus_example.py
. Before running it, let's ensure my_reading_file.txt
has its original content:
echo "This is the first line." > /home/labex/project/my_reading_file.txt
echo "This is the second line." >> /home/labex/project/my_reading_file.txt
Now, run the Python script from the terminal:
python rplus_example.py
You'll see the initial content printed, followed by messages about the process:
Initial file content:
This is the first line.
This is the second line.
Moving pointer to the beginning using file.seek(0).
Writing new content...
Truncating file to the current position to remove old trailing data.
Content written and file truncated.
Finished with r+ mode example.
Check the final file content using cat
:
cat /home/labex/project/my_reading_file.txt
The output should show only the newly written content, thanks to the overwrite and truncate:
Prepended line 1.
Prepended line 2.
Choosing the Appropriate File Access Mode
Selecting the correct mode is vital. Here's a quick guide:
- Use
'r'
for read-only access to existing files.
- Use
'w'
to create a new file or completely replace an existing file's content.
- Use
'a'
to add to the end of a file without losing existing data (good for logs).
- Use
'r+'
to read and modify an existing file from the beginning.
- Use
'w+'
to create or overwrite a file and then read/write it.
- Use
'a+'
to append to a file and also be able to read it (requires seeking).
This table summarizes the key behaviors:
Mode |
Read |
Write |
Create if not exists |
Truncate if exists |
Pointer Position (Initial) |
'r' |
Yes |
No |
No |
No |
Beginning |
'w' |
No |
Yes |
Yes |
Yes |
Beginning |
'a' |
No |
Yes |
Yes |
No |
End |
'r+' |
Yes |
Yes |
No |
No |
Beginning |
'w+' |
Yes |
Yes |
Yes |
Yes |
Beginning |
'a+' |
Yes |
Yes |
Yes |
No |
End |
By considering whether you need to read, write, append, handle existing files, or create new ones, you can confidently choose the most suitable mode for your task.