-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCSVHandler.py
More file actions
104 lines (83 loc) · 2.55 KB
/
CSVHandler.py
File metadata and controls
104 lines (83 loc) · 2.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
# -*- coding: utf-8 -*-
import csv
import io
class CSVFile(object) :
"""
A conveniant object that represents a CSV file.
"""
def __init__(self, path=None) :
self._headers = list()
self._data = dict()
if path :
self._load_file(path)
else :
#TODO : raise an exception
print("No path provided for the creation of the CSVFile object.")
@property
def headers(self):
return self._headers
@property
def data(self):
return self._data
def _load_file(self, path, template=None) :
"""
Loads the file pointed by `path` and populates the related properties. By default the function
considers the file to be a set of the form
header1 header2 header3 ... headerN
val11 val12 val13 val1N
val21 val22 val23 val2N
... ... ... ...
valM1 valM2 valM3 valMN
where headerX are str objects and valYX are float objects.
But one can provide a custom template if this does not meet your requirements.
"""
#TODO : implements the template feature.
# Hint : `template` could be a dictionary where keys are field names and values are values types.
# e.g. : template = {PRIM_X_CURRENT:float, ROOM_TYPE:str}
with open(path, 'rb') as my_file:
reader = csv.DictReader(my_file, dialect='excel', delimiter=',')
# Process the whole file and populate self._data
for line in reader :
for (k,v) in line.items():
if k not in self._data:
self._data[k] = [v]
else:
self._data[k].append(float(v)) # The float conversion is needed because the DictReader returns str values by default.
self._headers = reader.fieldnames
def to_file(self, path) :
"""
Generate a csv file based on the CSVFile object.
"""
pass
def __str__(self):
if len(self._headers) > 3 or len(self._data[self._headers[0]]) > 15 :
return "CSVFile object."
else :
result = ""
for h in self._headers :
result += h + " : " + str(self._data[h])
return result
class Field(CSVFile):
"""
A CSVFile object that represents a single field (column).
"""
def __init__(self, header=None, values=None) :
self._headers = [header]
self._title = header
self._data = dict()
self._data[header] = values
@property
def title(self):
return self._title
#========== TESTING ========== #
if __name__ == "__main__":
import sys
import os
if os.path.isfile(sys.argv[1]):
test_field = 8
c = CSVFile(sys.argv[1])
f = Field(header=c.headers[test_field], values=c.data[c.headers[test_field]])
print(c)
print(f)
else:
print("Error, the file does not exist")