[Python] Python csv DictReader with optional header

Discussão em 'Python' iniciado por Stack, Abril 15, 2025.

  1. Stack

    Stack Membro Participativo

    import csv
    import io


    FIELDNAMES = ['one', 'two', 'three']


    def print_data_rows(csvfile):
    reader = csv.DictReader(csvfile, fieldnames=FIELDNAMES)
    for row in reader:
    print(row)


    headerless = r'''
    1,2,3
    '''
    print_data_rows(io.StringIO(headerless.strip()))



    headerful = r'''
    one,two,three
    1,2,3
    '''
    print_data_rows(io.StringIO(headerful.strip()))


    I would like the output to be

    {'one': '1', 'two': '2', 'three': '3'}
    {'one': '1', 'two': '2', 'three': '3'}


    but actually the output is

    {'one': '1', 'two': '2', 'three': '3'}
    {'one': 'one', 'two': 'two', 'three': 'three'}
    {'one': '1', 'two': '2', 'three': '3'}


    because DictReader is not skipping the header row, when it exists.

    How can I skip the header row if it exists?

    Continue reading...

Compartilhe esta Página