1. File Handling Basics
The file handling process in Python
File Operations Workflow
- Open a file (creates file object)
- Read/Write data
- Close the file (release resources)
Always close files to prevent memory leaks and data corruption.
2. File Modes
Read Mode 'r'
Open for reading (default)
file = open("data.txt", "r")
Write Mode 'w'
Open for writing (overwrites)
file = open("data.txt", "w")
Append Mode 'a'
Open for appending
file = open("data.txt", "a")
Read/Write 'r+'
Open for both reading and writing
file = open("data.txt", "r+")
Exercise 1: File Mode Practice
Create a program that:
- Writes three lines to a new file
output.txt - Then reads and prints the file contents
3. Reading Files
Method 1: read()
Read entire file at once
with open("data.txt", "r") as file:
content = file.read()
print(content)
Method 2: readlines()
Read as list of lines
with open("data.txt", "r") as file:
lines = file.readlines()
for line in lines:
print(line.strip())
For large files, read line by line to avoid memory issues.
4. Writing Files
Write Mode 'w'
Overwrites existing content
with open("log.txt", "w") as file:
file.write("New log entry\n")
Append Mode 'a'
Adds to existing content
with open("log.txt", "a") as file:
file.write("Another entry\n")
Exercise 2: CSV Writer
Create a program that:
- Writes a list of dictionaries to CSV
- Format:
Name,Age,Occupation - Include headers
5. Essential File Methods
| Method | Description | Example |
|---|---|---|
read(size) |
Reads specified bytes | file.read(100) |
readline() |
Reads single line | file.readline() |
write() |
Writes string to file | file.write("text") |
seek() |
Changes file position | file.seek(0) |
tell() |
Returns current position | file.tell() |