Opening & Closing Files
Why File Handling?
Programs often need to work with data that persists beyond the program's execution. Files allow you to:
- Store data permanently on disk
- Read configuration settings
- Process large datasets
- Generate reports and logs
- Share data between programs
The open() Function
Python uses the built-in open() function to work with files. It returns a file object that you can use to read, write, or manipulate the file.
File Modes
The mode parameter determines how the file is opened:
| Mode | Description |
|---|---|
"r" |
Read (default) - File must exist |
"w" |
Write - Creates new file, overwrites if exists |
"a" |
Append - Adds to end of file, creates if not exists |
"r+" |
Read and Write - File must exist |
"w+" |
Write and Read - Creates/overwrites file |
"rb" / "wb" |
Binary mode (for images, executables, etc.) |
Always close files when you're done! Unclosed files can lead to data loss, resource leaks, and locked files. Python's context managers (covered in Section 4) handle this automatically.
Opening a file in write mode ("w") will erase all existing content! Use append mode ("a") if you want to add to existing files.
Practice opening a file and displaying information about it. The virtual file system has a file called "sample.txt" pre-loaded.
.name, .mode, and .closed that give you information about the file's state.
Reading Files
Reading Methods
Python provides several methods to read file content:
Reading Line by Line
For large files, reading line by line is more memory-efficient:
Iterating Over Files
The most Pythonic way to read files line by line is to iterate directly:
Each line read includes the newline character (\n) at the end. Use strip() to remove whitespace including newlines: line.strip()
Read the file "data.txt" and count the number of lines and total characters. The file contains multiple lines of text.
readlines() to get all lines as a list, then use len() to count them. For characters, loop through each line with strip() to remove newlines.
Writing Files
Writing Methods
Python provides methods to write content to files:
Writing Multiple Lines
Use writelines() to write a list of strings:
Appending to Files
Use append mode to add content without erasing existing data:
Opening a file in "w" mode will immediately erase all existing content, even before you write anything! Always double-check your file mode.
Create a file called "report.txt" and write a simple report with a title and three bullet points.
"w" mode to create/write. Remember to include \n at the end of lines for proper formatting.
Context Managers (with Statement)
The Problem with Manual Closing
What happens if an error occurs before close()?
If an error occurs, the file stays open, potentially causing resource leaks.
The Solution: with Statement
Python's with statement automatically handles file closing, even if errors occur:
Always use with statements for file operations. It's the Python standard and prevents resource leaks. The file is guaranteed to close when the indented block ends.
Working with Multiple Files
You can open multiple files in a single with statement:
Rewrite file operations using the with statement. Read "data.txt" and create "uppercase.txt" with the content in uppercase.
with statement syntax is: with open(filename, mode) as variable:. No need to call close() - it's automatic!
File Operations & Patterns
Common File Patterns
Here are some useful patterns you'll use frequently when working with files:
Checking if File Exists
Use the os module to check file existence before operations:
File Position (seek and tell)
You can move around within a file using seek() and check position with tell():
Working with CSV-like Data
A common pattern is reading structured text files:
Read "users.csv" (comma-separated data), filter users over age 25, and write them to "adults.txt".
split(",") to separate CSV fields. Convert age to int() for comparison. Build a list of adults, then write them all at once.
Chapter Summary
What You've Learned
In this chapter, you mastered Python file handling:
- Opening Files:
open(filename, mode)with various modes (r, w, a, r+) - Reading:
read(),readline(),readlines(), and iteration - Writing:
write()andwritelines() - Context Managers: The
withstatement for safe, automatic cleanup - File Operations: Position control, existence checks, data parsing
Quick Reference
1. Always use with statements for file operations.
2. Use "w" mode carefully - it overwrites existing files!
3. Remember to add \n for newlines when writing.
4. Use strip() to remove trailing newlines when reading.
Chapter 7 Complete!
Ready for the Practical Exam?
Put your file handling skills to the test with 3 coding challenges. Medium-Hard difficulty.
Take Chapter 7 Exam →