Introduction to File Handling
Imagine you have written a program that calculates a player’s high score in a video game. When the user closes the program, that score vanishes into thin air! How do you save it so it is still 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 Python program to read data from and write data to files on your computer’s persistent storage (like a hard drive or SSD). It acts as the bridge between your program’s temporary memory (RAM) and long-term, persistent storage.
Why is File Handling Essential?
Almost every real-world application needs to handle files in some way. It is a fundamental skill for making your programs useful and stateful:
Text Files vs. Binary Files
Python can handle two fundamental types of files, and it is crucial to understand the difference:
Text Files (Default)
Text Files ('t' mode)
- Content: Store data as human-readable sequences of characters.
- Encoding: When writing, Python encodes characters into bytes. When reading, it decodes bytes back into text characters. The default encoding is usually UTF-8.
- Line Endings: Python automatically handles the conversion of the newline character
\nto your specific operating system’s format (for example,\r\non Windows).
Example
Output:
Always be explicit about the mode you are using! If you are working with an image but forget to add 'b' to the mode (for example, using 'w' instead of 'wb'), Python will try to encode the image bytes as text, corrupting the file completely.