Tsallaka zuwa abun ciki
Justice Tech School

Reading Files

open(path) returns a file object. Use a with block so the file is closed automatically. read() gets everything, readline() one line and looping over the file gives lines. Pass encoding="utf-8" so special characters work everywhere.

Example
import tempfile, os
path = os.path.join(tempfile.mkdtemp(), "notes.txt")
with open(path, "w", encoding="utf-8") as f:
    f.write("first line\nsecond line\n")

with open(path, encoding="utf-8") as f:
    print(f.readline().strip())
    for line in f:
        print("rest:", line.strip())

Result

first line
rest: second line

Exercise

Make sure the file closes by itself.

 open("a.txt") as f:
    data = f.read()

Quiz Test

Why use a with block for files?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.