I'm trying to read in CSV file with csv.DictReader
to obtain dict data.
The problem is the file contains few lines of other data and the header for dictionary starts from nth row.
Is there way to specify the starting row when opening the csv file?
with open(filename, 'r') as f:
reader = csv.DictReader(f) #want to specify the starting row here
for row in reader:
...
CodePudding user response:
Since reader operates on an opened file object, you can just skip the lines yourself by calling readline()
in advance:
from io import StringIO
from csv import DictReader
data = StringIO(
"""linewedon'twant
linewedon'twant
x,y
0,1
1,5
2,10
"""
)
with data as f:
for _ in range(2):
f.readline()
reader = DictReader(f)
for row in reader:
print(row)
Obviously, with data as f
would be with open("csv") as f:
; I left it in here (where it isn't needed) to keep the structure the same.