list first 5 lines of file in python

We can use the open() function to read a file and then loop through the file object using the readline() function to print the first 5 lines. Here's the code:

main.py
with open('filename.txt', 'r') as f:
    for i in range(5):
        line = f.readline()
        print(line)
108 chars
5 lines

In the above code, we open the file using a with statement that automatically closes the file when we're done with it. We then loop through the file object 5 times using the range() function and readline() method to read and print each line.

gistlibby LogSnag