Labs ICT
Pro Login

Read Files

1 min read | Python Tutorial

Want the full learning experience?

Get structured courses, certificates, projects, and instructor support with LabsICT Pro.

Explore Pro Courses

Read Entire File with read()

read() returns the whole file content as a single string. Pass an integer to read only that many characters.

with open("example.txt", "w") as f:
    f.write("Line one\nLine two\nLine three")

with open("example.txt", "r") as f:
    data = f.read()
    print(data)

Read Line by Line with readline()

readline() reads one line at a time. Each call moves the file cursor to the next line. Returns an empty string at the end.

with open("example.txt", "r") as f:
    line1 = f.readline()
    line2 = f.readline()
    print(repr(line1), repr(line2))

Loop Through a File

A file object is iterable. Looping over it yields one line per iteration — efficient even for huge files.

with open("example.txt", "r") as f:
    for line in f:
        print(line.strip())