Introduction to File Handling
Imagine you’ve written a program that calculates a user’s high score in a game. When the user closes the program, that score vanishes. How do you save it so it’s there the next time they play? The answer is file handling.
File handling, or File I/O (Input/Output), is the process of using your program to read data from and write data to files on your computer’s storage (like a hard drive or SSD). It’s the bridge between your program’s temporary memory (RAM) and long-term, persistent storage.
Why is File Handling Essential?
Nearly every non-trivial application needs to handle files in some way. It’s a fundamental skill for making your programs useful and stateful.
Data Persistence
This is the most common use case. You can save your application’s state, user progress, or any other data so it can be retrieved later.
Pyground
Save a player's name and high score to a file named `highscore.txt`.
Expected Output:
High score saved successfully!
Output:
Text Files vs. Binary Files
Python can handle two fundamental types of files, and it’s crucial to understand the difference.
Text Files ('t'
mode - default)
- Content: Store data as human-readable sequences of characters (text).
- Encoding: When you write to a text file, Python encodes the characters into bytes. When you read, it decodes bytes back into characters. The default encoding is platform-dependent (often UTF-8), which can sometimes cause issues if files are moved between systems.
- Line Endings: Python automatically handles the conversion of the newline character
\n
to your operating system’s specific line ending (e.g.,\r\n
on Windows). - Use Cases:
.txt
files, source code (.py
), configuration files (.ini
), and structured data formats like.csv
and.json
.
Pyground
Write a few lines of text to a file named `diary.txt`.
Expected Output:
Wrote to diary.txt
Output:
Always be explicit about the mode you’re using. If you’re working with an image but forget to add 'b'
to the mode (e.g., using 'w'
instead of 'wb'
), Python will try to encode the image data as text, which will corrupt the file.