Labs ICT
Pro Login

Read Files

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)
Try it Yourself →

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))
Try it Yourself →

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())
Try it Yourself →