+2 votes
in Programming Languages by (75.9k points)

How can I read only the first line of an input file in Python?

E.g. 

My file has the following content and I want to just get the header.

name,age,sex

app,32,m

bee,12,f

mfg,23,m

1 Answer

+1 vote
by (353k points)
selected by
 
Best answer

You can use readline() or readlines() to get the first row of an input file. Here is an example using your input data.

Using readline()

with open('testfile.txt', 'r') as f:
    rec = f.readline()
print(rec)

Using readlines()

with open('testfile.txt', 'r') as f:
    rec = f.readlines()
print(rec[0].strip())

These codes will print the following:

name,age,sex


...