Introduction to File Handling
Overview
File handling lets Python programs save and access data beyond runtime. You'll learn why persistent storage is essential, the difference between text and binary files, and how to use them in everyday programs, enabling your code to work with real-world data.
What You Will Learn in This Lesson
By the end of this lesson, you will know:
- What file handling is: Understand why programs need to work with files.
- Persistent storage: Learn how files let data survive after your program ends.
- Text vs binary files: Understand the difference between these two file types.
- Common use cases: See when and why you'd use file handling in real programs.
- Basic concepts: Get familiar with reading, writing, and file operations.
Why Do We Need File Handling?
So far, all the data in your programs has been stored in variables. When your program ends, that data disappears. But what if you want to:
- Save user preferences for next time?
- Store a list of contacts or notes?
- Read data from a CSV file?
- Save game progress?
That's where file handling comes in. Files let your program save data to your computer's hard drive, so it persists even after the program closes.
Think of it Like This
Variables are like sticky notes — they're temporary and disappear when you're done. Files are like notebooks — they stay on your desk and you can read them again later.
What is Persistent Storage?
Persistent storage means data that stays saved even after your program stops running. When you save a file, it's written to your computer's hard drive, which means:
- The data survives program restarts
- You can share files between programs
- Data can be backed up and transferred
- Multiple programs can access the same file
Example: Without File Handling
# This data disappears when the program ends
user_name = "Alice"
score = 100
print(f"{user_name} scored {score} points")
# When program closes, user_name and score are gone!
Example: With File Handling
# This data can be saved to a file
user_name = "Alice"
score = 100
# Save to file (we'll learn how to do this)
# File: scores.txt contains "Alice,100"
# Next time program runs, we can read it back!
# Data persists even after program closes
Text Files vs Binary Files
Python can work with two main types of files:
Text Files
Text files contain human-readable characters. Examples include:
.txtfiles (plain text).csvfiles (comma-separated values).jsonfiles (structured data).pyfiles (Python code)
You can open these files in any text editor and read them directly.
Binary Files
Binary files contain data in a format that's not human-readable. Examples include:
.jpgor.pngfiles (images).mp3or.wavfiles (audio).exefiles (executable programs).zipfiles (compressed archives)
These files need special programs to read them.
For Beginners
We'll focus on text files first because they're easier to work with. Once you're comfortable with text files, binary files follow similar principles.
Common File Operations
When working with files, you'll typically do these operations:
1. Open
Tell Python which file you want to work with and how (read, write, etc.)
2. Read or Write
Get data from the file or save data to it
3. Close
Tell Python you're done with the file (important for saving changes!)
Basic File Operation Pattern
# 1. Open the file
file = open("data.txt", "r") # "r" means read mode
# 2. Read from the file
content = file.read()
# 3. Close the file
file.close()
Don't worry about understanding this code yet — we'll cover it in detail in the next lessons!
Real-World Examples
File handling is used everywhere in programming:
Text Editors
Save and load documents
Games
Save game progress and settings
Data Analysis
Read CSV files with data, process it, save results
Web Applications
Store user data, logs, and configuration files
Email Clients
Save drafts and read saved messages
Databases
Store structured data in files
Why File Handling Matters
Without file handling, every time you run a program, you'd have to re-enter all your data. File handling allows programs to:
- Remember user preferences between sessions
- Store large amounts of data efficiently
- Share data between different programs
- Create backups and archives
- Process data from external sources
File Handling Workflow
Understanding the typical workflow when working with files:
Identify the File
Determine which file you want to work with and where it's located (file path).
Choose the Mode
Decide what you want to do: read ('r'), write ('w'), or append ('a').
Open the File
Use open() to create a connection to the file.
Perform Operations
Read data from the file or write data to it using methods like read(), write(), etc.
Close the File
Always close the file when done to save changes and free resources. Better yet, use the with statement!
Important Concepts to Remember
Before we dive into the code, remember these key points:
1. Files Must Be Opened Before Use
You can't read or write to a file until you've opened it. Opening a file creates a connection between your program and the file. Think of it like opening a book before you can read it!
2. Always Close Files When Done
Closing a file ensures all changes are saved and frees up system resources. Forgetting to close files can cause problems like data loss or locked files. We'll learn the with statement to make this automatic!
3. File Paths Matter
You need to tell Python where the file is located. This could be a relative path (like "data.txt") or an absolute path (like "/Users/name/Documents/data.txt"). We'll cover paths in detail later.
4. Files Can Be Read-Only or Write-Only
When you open a file, you specify what you want to do with it. You can read from it, write to it, or both. This is called the "file mode" and prevents accidental overwrites.
5. Files Persist After Program Ends
Unlike variables, files remain on your computer after your program finishes. This is the whole point of file handling - to save data permanently!
Common File Operations Overview
Here's a preview of what you'll learn in the upcoming lessons:
Opening Files
Use open() to create a connection to a file. Specify the file path and mode (read, write, append).
Reading Files
Use methods like read(), readline(), and readlines() to get data from files.
Writing Files
Use write() and writelines() to save data to files.
Closing Files
Use close() or the with statement to properly close files and save changes.
What's Next?
In the next lessons, you'll learn:
- How to open files in different modes (read, write, append)
- Different ways to read file content
- How to write data to files
- Working with file paths across different operating systems
- Using the
withstatement for automatic file closing - Handling errors when working with files
End-of-Lesson Exercises
Think about these questions to reinforce what you've learned:
Exercise 1: Why Files?
Name three situations where you'd need to use file handling instead of just variables.
Exercise 2: File Types
List three examples of text files and three examples of binary files.