This shows you the differences between two versions of the page.
| Next revision | Previous revision | ||
| docu:csheet:sysadm:script:python:read_csv [2020/07/08 08:02] – created admin | docu:csheet:sysadm:script:python:read_csv [2022/01/05 13:48] (current) – admin | ||
|---|---|---|---|
| Line 2: | Line 2: | ||
| \\ | \\ | ||
| - | 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: | + | If you just want to **create your own code** from scratch, with the very **basic .csv reading code**, this is the snippet you need: |
| + | <code python> | ||
| + | def read_csv_data(fname): | ||
| + | with open(fname) as csvfile: | ||
| + | reader = csv.reader(csvfile, | ||
| + | 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: | ||
| <code python> | <code python> | ||
| Line 21: | Line 31: | ||
| if first: | if first: | ||
| for field in row: | for field in row: | ||
| - | # replace everything that is not [a-zA-Z0-9] or _ to ' | + | # replace everything that is not the < |
| # and also convert the field to lowercase | # and also convert the field to lowercase | ||
| - | fields.append(re.sub(r' | + | fields.append(re.sub(r' |
| + | first = False | ||
| else: | else: | ||
| i = 0 | i = 0 | ||
| Line 35: | Line 46: | ||
| i += 1 | i += 1 | ||
| data.append(item) | data.append(item) | ||
| - | first = False | ||
| return data | return data | ||
| return [] | return [] | ||
| </ | </ | ||