How to skip pre header lines with csv.DictReader?

后端 未结 2 1414
醉酒成梦
醉酒成梦 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: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)
    

提交回复
热议问题