2

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:
      ...
ysd
  • 191
  • 3
  • 12
  • Add the csv (or a subset of it) and explain the details. – balderman Oct 08 '21 at 09:38
  • Does this answer your question? [Skip the headers when editing a csv file using Python](https://stackoverflow.com/questions/14257373/skip-the-headers-when-editing-a-csv-file-using-python) – mkrieger1 Oct 08 '21 at 09:41
  • Sorry, it's rather this: https://stackoverflow.com/questions/9578580/skip-first-couple-of-lines-while-reading-lines-in-python-file – mkrieger1 Oct 08 '21 at 09:42
  • I don't think either of those are direct duplicates, as one is simply about reading, and the other works by iterating the _reader_ object (which isn't an option with `DictReader`, since it reads the first row for the key names. However, iterating the file *before* passing it to reader works fine – 2e0byo Oct 08 '21 at 10:04

1 Answers1

3

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.

2e0byo
  • 5,305
  • 1
  • 6
  • 26