-
Notifications
You must be signed in to change notification settings - Fork 33
/
file_io.py
111 lines (90 loc) · 2.4 KB
/
file_io.py
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
105
106
107
108
109
110
111
import csv
import json
import pickle
__all__ = [
"read_csv_to_dictionary",
"write_data_to_json",
"read_data_from_json",
"write_data_to_pickle",
"read_data_from_pickle",
]
def read_csv_to_dictionary(csvfile, delimiter=";"):
"""Reads a csv file and returns a dictionary with the respective keys
specified in the first row of the csv file.
Parameters
----------
csvfile : str
The path to csv file.
delimiter : str, optional
The character used to separate the values. Default ``;``
Returns
-------
dict
"""
data = []
with open(csvfile, mode="r") as infile:
reader = csv.reader(infile, delimiter=delimiter)
for rows in reader:
data.append(rows)
infile.close()
data = zip(*data) # transpose data
data_dict = {}
for col in data:
key = col[0]
values = list(col[1:])
data_dict.update({key: values})
return data_dict
def write_data_to_json(data, file):
"""Write data to json file.
.. deprecated:: 0.23
Use :func:`compas.data.json_dump` instead.
Parameters
----------
data : dict, list, tuple, str, unicode, int, long, float, boolean, None
The data to write to json file. Data must be JSON serialisable.
file : str
The path where to save the data.
"""
with open(file, "w") as f:
json.dump(data, f)
def read_data_from_json(file):
"""Read data from json file.
.. deprecated:: 0.23
Use :func:`compas.data.json_load` instead.
Parameters
----------
file : str
The path to the json file.
Returns
-------
object
An object containing the deserialised data from the json file.
"""
with open(file) as f:
data = json.load(f)
return data
def write_data_to_pickle(data, file):
"""Write data to pickle file.
Parameters
----------
data : object
The data to write to a pickle file.
file : str
The path where to save the data.
"""
with open(file, "wb") as f:
pickle.dump(data, f)
def read_data_from_pickle(file):
"""Read data from pickle file.
Parameters
----------
file : str
The path to the pickle file.
Returns
-------
object
An object containing the reconstituted object hierarchy.
"""
with open(file, "rb") as f:
data = pickle.load(f)
return data