CodeAgeBy Sitezack
Applied Python for ProsFiles, CSV and APIs0 XP
Chapter progress0/6

Lesson 2 of 7

Write and read files

open(path, "w") opens a file for writing; the with block guarantees it gets closed, even on error — it's the standard idiom.

Without a mode argument, open(path) reads: f.read() returns the whole content as a string.

with open("log.txt", "w") as f:
    f.write("line 1\n")

with open("log.txt") as f:
    print(f.read())

🎯 Exercise

Write the text alpha\nbeta\n (two lines) into the file notes.txt, then read it back into the variable content and print it.

PRO lesson

This advanced chapter is part of CodeAge PRO. Unlock it to keep your adventure going.

Discover PRO