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
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()
raja
Published on 22-Dec-2017 11:17:11
Advertisements