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,sexapp,32,mbee,12,fmfg,23,m
name,age,sex
app,32,m
bee,12,f
mfg,23,m
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: