User Tools

Site Tools


docu:csheet:sysadm:script:python:read_csv

This is an old revision of the document!


Read a CSV file to JSON, using the first rows as field names definition


In case we want to read a .csv file on python (3), and get a JSON (dictionary on python) with the first row defining the field names of each item, we can use this code snippet:

import csv
import re
 
def read_csv_data(fname):
    # open the csv file and create a reader
    with open(fname) as csvfile:
        reader = csv.reader(csvfile, delimiter=',')
        first = True
        fields = []
        data = []
 
        # iterate all rows on the csv
        for row in reader:
            # if dealing with first row, append each cell as fields
            if first:
                for field in row:
                    # replace everything that is not [a-zA-Z0-9] or _ to '_'
                    # and also convert the field to lowercase
                    fields.append(re.sub(r'[^\w]+', '_', field.lower()))
            else:
                i = 0
                item = {}
                # process an actual item on the list
                for cell in row:
                    try:
                        item[fields[i]] = cell
                    except IndexError:
                        pass
                    i += 1
                data.append(item)
                first = False
        return data
    return []
docu/csheet/sysadm/script/python/read_csv.1594195368.txt.gz · Last modified: 2020/07/08 08:02 by admin