Computer >> Computer tutorials >  >> Programming >> Python

How to read only the first line of a file with Python?


To read only the first line of a file, open the file in read mode and call readline method on the file object. For example,

f = open('my_file.txt', 'r')
line = f.readline()
print line
f.close()

The above code reads first line from my_file.txt and prints to stdout. A safer approach would be using the with open syntax to avoid file from not closeing in case of an exception:

with open('my_file.txt', 'r') as f:
    print f.readline()