Read and write files cleanly with with, exchange JSON and organize your code into importable modules.
Open this lesson in KodokonReading 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.
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)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.
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"]) # 3A 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.
def compute_total(prices):
return round(sum(prices), 2)
def main():
print(compute_total([9.99, 4.5, 20.0]))
if __name__ == "__main__":
main()python billing.py