- Understand file opening modes and operations
- Read files using different methods
- Write data to files safely
- Apply context managers and best practices
Reading and Writing Files
File Handling Fundamentals
Think of files as containers that hold information, like boxes storing different types of items. Some boxes hold text, others hold images or data. Understanding how to open, read from, and write to these containers is essential for data management.
Opening Files
The open() function is like unlocking a box. You specify the file path and mode (read, write, append, etc.).
# Open for reading (default)
file = open('example.txt', 'r')
# Open for writing
file = open('example.txt', 'w')
# Open for appending
file = open('example.txt', 'a')
Reading Files
Reading Entire File
with open('example.txt', 'r') as file:
content = file.read()
print(content)
Reading Line by Line
with open('example.txt', 'r') as file:
for line in file:
print(line.strip())
Reading Specific Amount
with open('example.txt', 'r') as file:
chunk = file.read(100) # Read first 100 characters
Writing Files
Writing Text
with open('example.txt', 'w') as file:
file.write("Hello, World!\n")
file.write("This is a new line.")
Writing Multiple Lines
lines = ["Line 1", "Line 2", "Line 3"]
with open('example.txt', 'w') as file:
file.writelines(line + '\n' for line in lines)
Context Managers
Using with statements automatically handles file closing, even if errors occur. It's like having a self-locking box.
File Modes
| Mode | Description |
|---|---|
| 'r' | Read (default) |
| 'w' | Write (truncates file) |
| 'a' | Append |
| 'x' | Exclusive creation |
| 'b' | Binary mode |
| 't' | Text mode (default) |
Managing Log Files Example
Imagine maintaining a journal. You might:
- Read previous entries to review your thoughts
- Add new entries at the end
- Occasionally rewrite sections
- Back up important entries to another file
Best Practices
- Always use
withstatements for file operations - Specify encoding when working with text files
- Handle potential IO errors gracefully
- Close files explicitly if not using context managers
- Be careful with write modes to avoid accidental data loss
Mastering file reading and writing gives you the ability to persist and retrieve data, making your programs more powerful and useful.
