+2 votes
in Programming Languages by (11.5k 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

0 votes
by (20k points)

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

...