-
Notifications
You must be signed in to change notification settings - Fork 4
/
file_handling.py
executable file
·86 lines (63 loc) · 2.46 KB
/
file_handling.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
import os
import json
import codecs
import pickle
import numpy as np
from scipy import sparse
def makedirs(directory):
if not os.path.exists(directory):
os.makedirs(directory)
def write_to_json(data, output_filename, indent=2, sort_keys=True):
with codecs.open(output_filename, 'w', encoding='utf-8') as output_file:
json.dump(data, output_file, indent=indent, sort_keys=sort_keys)
def read_json(input_filename):
with codecs.open(input_filename, 'r', encoding='utf-8') as input_file:
data = json.load(input_file, encoding='utf-8')
return data
def read_jsonlist(input_filename):
data = []
with codecs.open(input_filename, 'r', encoding='utf-8') as input_file:
for line in input_file:
data.append(json.loads(line, encoding='utf-8'))
return data
def write_jsonlist(list_of_json_objects, output_filename, sort_keys=True):
with codecs.open(output_filename, 'w', encoding='utf-8') as output_file:
for obj in list_of_json_objects:
output_file.write(json.dumps(obj, sort_keys=sort_keys) + '\n')
def pickle_data(data, output_filename):
with open(output_filename, 'wb') as outfile:
pickle.dump(data, outfile, pickle.HIGHEST_PROTOCOL)
def unpickle_data(input_filename):
with open(input_filename, 'rb') as infile:
data = pickle.load(infile)
return data
def read_text(input_filename):
with codecs.open(input_filename, 'r', encoding='utf-8') as input_file:
lines = input_file.readlines()
return lines
def write_list_to_text(lines, output_filename, add_newlines=True, add_final_newline=False):
if add_newlines:
lines = '\n'.join(lines)
if add_final_newline:
lines += '\n'
else:
lines = ''.join(lines)
if add_final_newline:
lines[-1] += '\n'
with codecs.open(output_filename, 'w', encoding='utf-8') as output_file:
output_file.writelines(lines)
def save_sparse(sparse_matrix, output_filename):
assert sparse.issparse(sparse_matrix)
if sparse.isspmatrix_coo(sparse_matrix):
coo = sparse_matrix
else:
coo = sparse_matrix.tocoo()
row = coo.row
col = coo.col
data = coo.data
shape = coo.shape
np.savez(output_filename, row=row, col=col, data=data, shape=shape)
def load_sparse(input_filename):
npy = np.load(input_filename)
coo_matrix = sparse.coo_matrix((npy['data'], (npy['row'], npy['col'])), shape=npy['shape'])
return coo_matrix.tocsc()