The following solutions are inspired by this answer. The output content in the examples below is generated using the following input data:
data.csv
Id,name,age,height,weight
1,Alice,20,62,120.6
2,Freddie,21,74,190.6
3,Bob,17,68,120.0
In case you would like to pretty print the output in the examples given below, you could use the following:
import json
print(json.dumps(data, indent=4, sort_keys=True, default=str))
Solution 1 - Use csv.reader()
to get a list of list
objects
import csv
def read_csv(filepath: str):
data = []
with open(filepath, 'r') as f:
reader = csv.reader(f, delimiter=',')
for row in reader:
data.append(row)
return data
data = read_csv('data.csv')
print(data)
Output
[['Id', 'name', 'age', 'height', 'weight'], ['1', 'Alice', '20', '62', '120.6'],
['2', 'Freddie', '21', '74', '190.6'], ['3', 'Bob', '17', '68', '120.0']]
To print the data line by line, you could also use the following:
print('\n'.join(', '.join(map(str,row)) for row in data))
Output:
Id, name, age, height, weight
1, Alice, 20, 62, 120.6
2, Freddie, 21, 74, 190.6
3, Bob, 17, 68, 120.0
Solution 2 - Use csv.DictReader()
to get a list of dict
objects
import codecs
import csv
def read_csv(filepath):
with open(filepath, 'rb') as f:
reader = csv.DictReader(codecs.iterdecode(f, 'utf-8'))
data = list(reader)
return data
data = read_csv('data.csv')
print(data)
Output
[{'Id': '1', 'name': 'Alice', 'age': '20', 'height': '62', 'weight': '120.6'},
{'Id': '2', 'name': 'Freddie', 'age': '21', 'height': '74', 'weight': '190.6'},
{'Id': '3', 'name': 'Bob', 'age': '17', 'height': '68', 'weight': '120.0'}]
Solution 3 - Use csv.DictReader()
to get a dictionary of dict
objects based on a primary key
import codecs
import csv
def read_csv(filepath):
data = {}
with open(filepath, 'rb') as f:
reader = csv.DictReader(codecs.iterdecode(f, 'utf-8'))
for row in reader:
key = row['Id'] # Assuming a column named 'Id' to be the primary key
data[key] = row
return data
data = read_csv('data.csv')
print(data)
Output
{'1': {'Id': '1', 'name': 'Alice', 'age': '20', 'height': '62', 'weight': '120.6'},
'2': {'Id': '2', 'name': 'Freddie', 'age': '21', 'height': '74', 'weight': '190.6'},
'3': {'Id': '3', 'name': 'Bob', 'age': '17', 'height': '68', 'weight': '120.0'}}
Pretty printed output (using the code mentioned at the top of this answer):
{
"1": {
"Id": "1",
"age": "20",
"height": "62",
"name": "Alice",
"weight": "120.6"
},
"2": {
"Id": "2",
"age": "21",
"height": "74",
"name": "Freddie",
"weight": "190.6"
},
"3": {
"Id": "3",
"age": "17",
"height": "68",
"name": "Bob",
"weight": "120.0"
}
}