Kodokon kodokon.com

Files and modules: with, import, organization

Read and write files cleanly with with, exchange JSON and organize your code into importable modules.

10 min · 3 questions

Open this lesson in Kodokon

Reading and writing files is the daily bread of a real program: exports, logs, configurations. The with keyword opens the file and guarantees it is closed, even if an error occurs in the middle of the block. It's the only professional way to open a file: without it, a forgotten close() can corrupt data or exhaust system resources.

PYTHON
lines = ["alpha", "beta", "gamma"]

with open("notes.txt", "w", encoding="utf-8") as f:
    for line in lines:
        f.write(line + "\n")

with open("notes.txt", encoding="utf-8") as f:
    content = f.read()

print(content)
The 'w' mode writes by overwriting the content; with no mode, you read.

For structured data, don't invent your own format: the json module from the standard library converts dictionaries and lists into text, and back. It's the universal exchange format between programs, APIs and configuration files.

PYTHON
import json

config = {"debug": True, "retries": 3}

with open("config.json", "w", encoding="utf-8") as f:
    json.dump(config, f, indent=2)

with open("config.json", encoding="utf-8") as f:
    loaded = json.load(f)

print(loaded["retries"])  # 3
json.dump writes the structure, json.load rebuilds it.

A module is simply a .py file: import billing loads billing.py and runs its content only once. Organize your code by responsibility - one module for billing, another for storage - and keep the import statements at the top of the file. The if __name__ == "__main__" test distinguishes two situations: when run directly, the file executes this block; when imported, it ignores it.

PYTHON
def compute_total(prices):
    return round(sum(prices), 2)

def main():
    print(compute_total([9.99, 4.5, 20.0]))

if __name__ == "__main__":
    main()
Content of billing.py: importable anywhere, runnable directly.
BASH
python billing.py
Run this way, the file executes main(); imported, it does nothing.

Knowledge check

Make sure you remember the key points of this lesson.

  1. What is the main advantage of with open(...) over open() alone?
    • The file is closed automatically, even in case of an error
    • Reading the file is faster
    • The file is created if it doesn't exist, whatever the mode
  2. What is the difference between the "w" and "a" modes?
    • "w" overwrites existing content, "a" appends to the end
    • "w" writes text, "a" writes binary
    • "w" creates the file, "a" fails if it doesn't exist
  3. What is the if __name__ == "__main__" test for?
    • To check that the file is indeed named main.py
    • To run a block only when the file is launched directly
    • To prevent the module from being imported by other files