User Tools

Site Tools


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

If you just want to create your own code from scratch, with the very basic .csv reading code, this is the snippet you need:

def read_csv_data(fname):
    with open(fname) as csvfile:
        reader = csv.reader(csvfile, delimiter=',')
        for row in reader:

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 the <regex>
                    # and also convert the field to lowercase
                    fields.append(re.sub(r'[^\w\.\-]+', '_', field.lower()))
                first = False
                i = 0
                item = {}
                # process an actual item on the list
                for cell in row:
                        item[fields[i]] = cell
                    except IndexError:
                    i += 1
        return data
    return []
docu/csheet/sysadm/script/python/read_csv.txt · Last modified: 2022/01/05 13:48 by admin