/
fileio.py
62 lines (52 loc) · 1.77 KB
/
fileio.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
import os
import datetime
import subprocess
from log import debug_log
import settings # debug
BANK_PATH = 'graph_bank/'
def write_graph(graph):
'''write the graph to a file.
Argument:
graph: a dictiction representation of a
graph.
Return:
None
'''
latest_file_name = 'path_dict_result.txt'
# write results to a file.
# latest_file_name is the file that stores the lastest
# result.
with open(latest_file_name, 'w') as result_file:
if settings.debug:
debug_log('writing path dict to file')
result_file.write(str(graph))
# create a unique name for each file in the graph_bank
basename = BANK_PATH + 'graph'
suffix = datetime.datetime.now().strftime('%y%m%d%H%M%S')
filename = '_'.join([basename, suffix]) + '.txt'
# copy the lastest result file to the graph_bank
subprocess.run(['cp', latest_file_name, filename])
def read_all_graphs():
'''Read all graph files into a dictionary.
Return:
a dictionary containing all the dictionaries in the graph bank.
'''
ret_dict = {}
for graph_file in os.listdir(BANK_PATH):
if graph_file.startswith('graph'):
graph_file_rel = BANK_PATH + graph_file
tmp_dict = read_graph(graph_file_rel)
ret_dict.update(tmp_dict)
return ret_dict
def read_graph(graph_file):
'''Read graph from a given file.
Arguments:
graph_file: a .txt file containing a stringified dictionary
representation of a graph.
Return:
a dictionary equivalent to the content of the given graph.
'''
with open(graph_file) as gf:
# We assume that all graph_files are not polluted and
# people are nice.
return eval(gf.read())