Python
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax and Data Types
-
Section 3: Collections
-
39: Set Operations: Union, Intersection, Difference
-
Section 4: Control Flow
-
Section 5: Functions
-
Section 6: Turtle Graphics and Early Practice Projects
-
Section 7: Working with Files and I/O
-
Section 8: Regular Expressions
-
Section 9: Object-Oriented Python
-
Section 10: Error Handling
-
Section 11: Modules and Packages
-
Section 12: Iterators, Generators, and Functional Tools
-
Section 13: Decorators and Metaprogramming
-
Section 14: Concurrency and Parallelism
-
Section 15: Working with Dates, Times, and Numbers
-
Section 16: Standard Library Deep Dive I: Data Structures
-
Section 17: Standard Library Deep Dive II: System and Introspection
-
Section 18: Standard Library Deep Dive III: Security and Encoding
-
Section 19: Standard Library Deep Dive IV: Text and Data Utilities
-
Section 20: Networking and Web Basics
-
Section 21: Working with Databases
-
Section 22: Testing and Quality
-
Section 23: Advanced Typing
-
Section 24: Context Managers and Resource Handling
-
Section 25: Text, Unicode, and Binary Data
-
Section 26: More Functional and Iteration Tools
-
Section 27: Data Validation and Configuration
-
Section 28: Working with Images and Media
-
Section 29: Property-Based and Documentation Testing
-
Section 30: Packaging and Deployment
-
Section 31: Performance and Internals
-
Section 32: Design Patterns in Python
-
Section 33: GUI Programming
-
Section 34: Security Basics
-
Section 35: Data Structures and Algorithms
-
Section 36: Practical Projects
-
Section 37: Capstone Projects
-
Section 38: Interview and Algorithm Practice
-
Section 39: Writing Idiomatic Python
92: Reading and Writing Text Files
A few years ago, I was reviewing code for a junior dev who had built a surprisingly complex task manager. It was great—until I realized that every time he restarted the script, all the tasks vanished. He had stored everything in a list in memory, forgetting that RAM is volatile. I remember the look on his face when I asked, "Where is the data actually saved?" He hadn't realized that for a program to be useful in the real world, it needs a way to "remember" things after the power goes out. That's where file I/O comes in.
Managing the File Lifecycle with Context Managers
In the old days, you'd open a file and then have to remember to explicitly call .close() at the end. If your code crashed before it hit that line, the file could stay locked by the OS, or worse, you'd end up with corrupted data. I almost lost a whole afternoon of work once because of a leaked file handle in a long-running loop.
Now, we use the with statement. It creates what we call a context manager. It essentially tells Python: "Open this file, let me do some work, and no matter what happens—even if the code crashes—close it the second I'm out of this block." It's cleaner, safer, and frankly, the only way you should be handling files in modern Python.
# This is the gold standard for opening files
with open("system_logs.txt", "r") as file:
content = file.read()
# The file is automatically closed here, even without calling .close()
Pulling Data Out of a Text File
When you open a file for reading (using the "r" mode), you have a few choices on how to get the data. You can use .read() to grab the entire file as one giant string, but be careful—if you try to read a 2GB log file into a string, your computer's fans are going to start screaming.
The more professional way to handle text files is to iterate over the file object itself. This reads the file line by line, which is incredibly memory-efficient. I always prefer this approach because it scales; it doesn't matter if the file is ten lines or ten million lines long.
with open("user_data.txt", "r") as file:
for line in file:
# .strip() removes the newline character (\n) from the end of each line
print(f"Processing record: {line.strip()}")
Persisting Your Data to Disk
Writing to files is where things get dangerous if you aren't paying attention to your "modes." If you open a file with "w" (write mode), Python completely wipes the existing file the moment you open it. I've seen developers accidentally delete an entire configuration file because they used "w" when they meant to add a new line to the end of it.
If you want to keep what's already there and just add new data, use "a" for append mode. This moves the "cursor" to the very end of the file. Here is how I usually handle basic logging or data persistence:
# Overwriting/Creating a new file
with open("settings.conf", "w") as file:
file.write("theme=dark\n")
file.write("notifications=off\n")
# Adding to an existing file without destroying it
with open("activity_log.txt", "a") as file:
file.write("User logged in at 10:00 AM\n")
📋 Practical Task
Build a Persistent Guestbook Application
Your task is to create a simple guestbook program that allows users to leave their name and a short message. The program must ensure that the messages are saved to a file so they aren't lost when the program closes.
Requirements:
- The program should prompt the user to enter their name and a message.
- Save these entries into a file named
guestbook.txtusing append mode, so that new entries don't delete previous ones. Each entry should be on a new line (e.g.,"Alice: Hello there!"). - After saving the new entry, the program should read the
guestbook.txtfile and print all previous entries to the console to show the updated list. - Use the
with open(...)context manager for all file operations.
There are no comments for now.