File I/O
Python provides the built-in open() function for working with files. Always use the with statement so files are closed automatically.
When working with files, it is important to understand the available access modes. The mode "r" is used to read an existing file, "w" to write (creates a new file or overwrites an existing one), "a" to append data to the end of a file without deleting previous content, and binary modes ("rb"/"wb") for non-text files such as images or audio. Choosing the right mode prevents data loss and runtime errors.
Another important concept is the context manager (with). When using with, Python automatically closes the file after the code block finishes, even if an error occurs. This is safer than calling f.close() manually. Python also provides other reading methods such as f.readline() to read one line, f.readlines() to read all lines as a list, and f.write() to write a string to a file.
File Access Modes:
| Mode | Description |
|---|---|
"r" |
Read (default) |
"w" |
Write (overwrite) |
"a" |
Append |
"rb"/"wb" |
Binary |
Code Example
# Writing a file
with open("data.txt", "w") as f:
f.write("Hello, Python!\n")
f.write("Second line\n")
# Reading a file
with open("data.txt", "r") as f:
content = f.read()
print(content)
# Reading line by line
with open("data.txt") as f:
for line in f:
print(line.strip())
# Appending to a file
with open("data.txt", "a") as f:
f.write("Third line\n")
Code Explanation
The first lines create the file data.txt in "w" (write) mode. The f.write() function writes the strings "Hello, Python!" and "Second line" into the file, each ending with \n for a new line. Next, the file is read in "r" mode using f.read(), which returns the entire file content as a single string. The line-by-line reading method uses a for loop directly on the file object, which is more efficient for large files because only one line is kept in memory at a time. Finally, "a" mode is used to append "Third line" without deleting previous data.
Everyday Example
A simple diary application can use file operations to save and read user notes. When a user writes a new note, the application opens the file in "a" mode and appends the note text with a timestamp. When the user wants to view all notes, the application reads the file in "r" mode and displays each line. A search feature can be added by reading all lines and then filtering with a specific keyword. All these operations use with open() so files are always closed safely.
Summary
File I/O operations in Python are easy to use thanks to the open() function and the with context manager. Understanding the various file access modes and the right reading and writing methods makes persistent data management efficient and safe.