← all tutorials

Working with files: reading and writing safely

Every real script eventually needs to read something someone handed you — a client list, a batch of notes — or produce something you can hand back: a summary, a log, a letter. That’s file handling, and Python has one pattern you’ll reuse for almost all of it.

Opening a file, the safe way

with open("clients.txt") as f:
    contents = f.read()

The with block opens the file, and guarantees it gets closed again the moment the block ends — even if something goes wrong partway through. It’s the same instinct as always returning a client’s original documents before you leave the room, whatever happened in the meeting. You very rarely need to close a file yourself; with does it for you.

Reading it line by line

with open("clients.txt") as f:
    for line in f:
        print(line.strip())

A file behaves like a list of lines when you loop over it. .strip() trims the invisible newline character left on the end of each line — without it, you’d see an extra blank line after everything you print.

Writing to a file

with open("summary.txt", "w") as f:
    f.write("Reviewed 3 client files today.\n")

The second argument, "w", means write — and it starts the file empty, overwriting whatever was there before. If you want to add to the end of an existing file instead of erasing it, use "a" for append. Knowing which one you meant matters far more here than it does most places in this course: get it backwards and you can genuinely lose a file’s contents.

A note on this browser console

The console on this page can’t reach your actual computer’s files — there’s no clients.txt sitting next to it, and there never will be; that’s a deliberate safety limit of running Python in a browser. So the exercise below simulates a file’s contents with a triple-quoted string instead. The moment you run the same code on your own machine against a real file, it behaves identically — with open(...) doesn’t change, only where the text comes from does.

file_contents = """Okafor & Sons
Meridian Health Trust
Brightwell Logistics"""

for line in file_contents.splitlines():
    print(f"Following up with {line}")

.splitlines() breaks a block of text into a list of lines, exactly like looping over an open file does — it’s the same pattern from the previous lesson, just fed by a string instead of a file for now.

What you just learned

with open(...) opens a file and guarantees it closes safely afterwards; looping over it gives you one line at a time; "w" and "a" decide whether you overwrite or add to what’s already there. The console here can’t touch real files, but everything you just practised transfers directly the moment you run it on your own machine.

Try it yourself

main.pyPython 3 · in your browser
You can't break anything.