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

PythonServer Side ProgrammingProgramming

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

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()
Updated on 01-Oct-2019 11:45:53