Learn Python in 30 Days — Day 18: Working with Files

Learn Python in 30 Days — Day 18: Working with Files

Welcome to Day 18 of the Learn Python in 30 Days series!

Yesterday you learned how to handle errors and build a debugging mindset.
Today, we take the next step by interacting with real files on your computer.

File handling is one of the most useful skills in programming.
It lets your programs save data, load it later, and store information permanently not just while your script is running.

All example files for this series are available on my GitHub: Learn-Python-in-30-Days

By the end of today, you’ll know how to:

  • Read text files

  • Write and append to files

  • Use the with open() pattern

  • Avoid common pitfalls

  • Build a Simple Notes App that saves your notes automatically

Step 1 — Why File Handling Matters

Everything from games to websites to apps needs to keep track of information:

  • Saving game progress

  • Logging errors

  • Storing lists, settings, scores, notes

  • Loading configuration files

  • Writing output for users

Python makes file handling surprisingly accessible.
You only need one function to start:

open("filename.txt")

Let’s build from that.

Step 2 — Reading Files

To read a file, you open it in "r" mode (read mode):

with open("example.txt", "r") as f: content = f.read() print(content)

What’s happening?

  • open() loads the file

  • "r" = read mode

  • with automatically closes the file afterwards

  • f.read() returns everything inside

Note: - For this to work you need the text file "example.txt" in the same folder as the save python script.
I filled mine with "Hello World!!"

Try it yourself, hopefully you'll see something like that shown below: -
You can also download this example from my GitHub here and run it yourself.

Reading line-by-line (useful for large files)

with open("example.txt", "r") as f: for line in f: print(line.strip())

Step 3 — Writing Files

To write to a file, use "w" mode:

with open("example.txt", "w") as f: f.write("Hello from Python!")

Be careful: "w" wipes the file before writing.

Try it yourself, hopefully you'll see something like that shown below: -


You can also download this example from my GitHub here and run it yourself.

Step 4 — Appending Files

Using "a" mode lets you add to the end and not overwrite the current contents:

with open("example.txt", "a") as f: f.write("\nAnother line added.")

This is great for logs, notes, lists, etc.

Try it yourself, hopefully you'll see something like that shown below: -

You can also download this example from my GitHub here and run it yourself.

Step 5 — Reading and Writing Safely

Python's with open(...) is the gold standard because:

  • It automatically closes the file

  • It avoids memory leaks

  • It prevents locked files

  • It keeps your code clean

Bad (don’t do this):

f = open("example.txt", "r") content = f.read() # forgot f.close()

Good:

with open("example.txt", "r") as f: content = f.read()

Step 6 — Mini-Project: Simple Notes App

Let’s tie everything together.

You’re going to build a tiny command-line notes app that can do the following:

  • Saves notes to a file

  • Loads notes on startup

  • Lets you add new notes

  • Stores everything permanently

File: -

NOTES_FILE = "notes.txt" def load_notes(): """Read all notes from the file.""" try: with open(NOTES_FILE, "r") as f: return f.read().splitlines() except FileNotFoundError: return [] # Create a new empty notes file later def save_notes(notes): """Write the entire list of notes back to the file.""" with open(NOTES_FILE, "w") as f: for note in notes: f.write(note + "\n") def show_notes(notes): if not notes: print("\nNo notes yet.\n") else: print("\nYour Notes:") for i, note in enumerate(notes, 1): print(f"{i}. {note}") print() def main(): notes = load_notes() while True: print("=== Simple Notes App ===") print("1. View Notes") print("2. Add Note") print("3. Exit") choice = input("Choose an option: ") if choice == "1": show_notes(notes) elif choice == "2": new_note = input("Type your note: ") notes.append(new_note) save_notes(notes) print("Note added!\n") elif choice == "3": print("Goodbye!") break else: print("Invalid choice.\n") main()

How it works:

  • On startup, it tries to read notes.txt

  • If the file doesn’t exist, it creates a fresh notes list

  • Each new note is saved instantly

  • Notes persist between runs, making your first real “stateful” program!

Try it yourself, hopefully you'll see something like that shown below: -

You can also download this example from my GitHub here and run it yourself.

Day 18 Wrap-Up

Today you learned:

  • How to read and write files safely

  • When to use "r", "w", and "a"

  • Why with open() is crucial

  • How to build a real persistent program: Simple Notes App

You've just unlocked one of the most powerful abilities in programming, storing data in the real world.

Next Up — Day 19 – Using Modules

Tomorrow (Day 19), you’ll explore modules like math, random, and datetime, which make your programs smarter and more capable.

All example files for this series are available on my GitHub: Learn-Python-in-30-Days

You can see the full series here Learn Python in 30 Days series!

Hope you have enjoyed this post, thanks Matty

Comments

Popular posts from this blog

Math Behind Logic Gates

6502 - Part 2 Reset and Clock Circuit

Building a 6502 NOP Test