How to skip pre header lines with csv.DictReader?

后端 未结 2 1415
醉酒成梦
醉酒成梦 2020-12-20 13:33

I want to csv.DictReader to deduce the field names from the file. The docs say \"If the fieldnames parameter is omitted, the values in the first row of the

相关标签:
2条回答
  • 2020-12-20 14:06

    After f.seek(0), insert:

    next(f)
    

    to advance the file pointer to the second line before initializing the DictReader.

    0 讨论(0)
  • 2020-12-20 14:16

    I used islice from itertools. My header was in the last line of a big preamble. I have passed preamble and used hederline for fieldnames:

    with open(file, "r") as f:
        '''Pass preamble'''
        n = 0
        for line in f.readlines():
            n += 1
            if 'same_field_name' in line: # line with field names was found
                h = line.split(',')
                break
        f.close()
        f = islice(open(i, "r"), n, None)
    
        reader = csv.DictReader(f, fieldnames = h)
    
    0 讨论(0)
提交回复
热议问题