Skip to content
    Pythonia

    FILE HANDLING · 7 MIN

    File Handling

    open() reads and writes files; with closes them automatically.

    PYRA explains

    • Modes: "r" read, "w" write (overwrites), "a" append.
    • with open(path) as f: guarantees the file is closed even if an error occurs.
    • f.read() reads everything; looping over f reads one line at a time — better for big files.

    Real world: Saving a game's high score so it's still there tomorrow.

    Code

    with open("notes.txt", "w") as f:
        f.write("line one\nline two\n")
    with open("notes.txt") as f:
        lines = [l.strip() for l in f]
    print(len(lines), lines[1])
    Output ›
    2 line two
    Try it in the online compiler →

    Checkpoint quiz

    Which mode adds to the end of an existing file?