Working with Files
Why Work with Files?
Storing Data Permanently
Until now, we've used variables to store data. However, variables are temporary and disappear once the program stops running. To keep data like user logs, high scores, or settings forever, we must use files.
Welcome to the world of permanent data. Variables are great for quick calculations, but they vanish when your script ends. To save information for the long haul, we need to learn how to interact with files on your computer.
- Variables are temporary (RAM-based).
- Files allow for permanent data storage (Disk-based).
- Python interacts with files using built-in functions.
The open() Function & Modes
Opening the Door
To talk to a file, you use the open() function. You must specify a mode to tell Python your intentions.
- 'r' (Read): View existing content.
- 'w' (Write): Overwrite everything or create new.
- 'a' (Append): Add to the end without deleting.
Before you can read or write, you must open the file. The open function takes two main arguments: the filename and the mode. Let's see how these modes behave differently. The 'r' mode is for reading. If the file doesn't exist, Python will stop and report an error. Warning! The 'w' mode is destructive. It wipes the file completely before writing new data. Use it carefully! The 'a' mode is safer for logs. It simply moves the cursor to the end and adds your new content.
- open('filename', 'mode') is the standard syntax.
- 'r' is the default mode.
- 'w' is destructive—it wipes the file clean.
The 'with' Statement
Safe File Handling
In the past, you had to manually close() files. If your code crashed, the file could break. Today, we use context managers via the with statement.
Think of the 'with' statement as a responsible assistant. It opens the file for you, lets you work inside an indented block, and automatically closes the door the moment you are done. This prevents data corruption.
- The 'with' statement automatically closes the file.
- It protects data even if the program crashes.
- It is considered the modern Python 'best practice'.
The Guest Book Project
Interactive Guest Book
Let's build a simple guest book. Use the buttons to write a new list or append a name to it.
Let's try a practical example. We have a file called guests.txt. Use the controls to manage the names in our guest book. You used 'w' mode. Notice how the previous names were deleted and replaced by your new entry. Great choice. Using 'a' mode kept the old names and added the new one at the bottom.
- Use 'w' to start fresh.
- Use 'a' to keep previous entries.
- Reading displays the final result.
Handling Newlines & Errors
Watch Your Step!
Python doesn't automatically add new lines. You must use the \n character. Also, be prepared for the FileNotFoundError when reading.
There are two common traps for beginners. First, if you don't use backslash-n, your text will bunch up on one line. Second, trying to read a file that isn't there will trigger a FileNotFoundError.
- \n creates a line break.
- Reading a missing file crashes the program.
- Always verify your file path.
Fix the Script
This script is supposed to add 'Charlie' to an existing list of guests, but it has a bug. Fix the mode and ensure it starts on a new line.
Look at this code. It's currently using the wrong mode and missing a newline. Correct the script to successfully append Charlie to our list.
- Identify the correct mode for adding data.
- Apply the newline character.
Lesson Summary
You've Mastered Files!
You can now save and retrieve data permanently. This is a huge step toward building real-world applications.
Great job! You've learned how to make your data persist beyond the life of a single script. Remember to always use the 'with' statement and double-check your file modes. You're now ready to move on to Object-Oriented Programming!
- Use 'with' for safe handling.
- Choose 'r', 'w', or 'a' based on your goal.
- Don't forget the \n for readability.