Reading and Writing Files
Use with open() so the file closes. Modes r, w, a add text. read, readline and iteration read content.
Example
import tempfile, os
p = os.path.join(tempfile.gettempdir(), "demo.txt")
with open(p, "w") as f:
f.write("one\ntwo\n")
with open(p) as f:
for line in f:
print(line.strip())
os.remove(p)Result
one two
Exercise
Append mode.
open(p, "")
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.