Skip to Content
Course content

92: Reading and Writing Text Files

Click on the "Edit" button in the top corner of the screen to edit your slide content.

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.txt using 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.txt file and print all previous entries to the console to show the updated list.
  • Use the with open(...) context manager for all file operations.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.