User Tools

Site Tools


docu:csheet:sysadm:script:python:read_csv

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:
            print(row)


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.txt · Last modified: 2020/07/08 08:05 by admin