User Tools

Site Tools


docu:csheet:sysadm:script:python:read_csv

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Next revision
Previous revision
docu:csheet:sysadm:script:python:read_csv [2020/07/08 08:02]
admin created
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, delimiter=','
 +        for row in reader: 
 +            print(row) 
 +</code> 
 + 
 +\\ 
 +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 <regex>
                     # and also convert the field to lowercase                     # and also convert the field to lowercase
-                    fields.append(re.sub(r'[^\w]+', '_', field.lower()))+                    fields.append(re.sub(r'[^\w\.\-]+', '_', field.lower())) 
 +                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 []
 </code> </code>
docu/csheet/sysadm/script/python/read_csv.1594195368.txt.gz · Last modified: 2020/07/08 08:02 by admin