forked from mscroggs/KLBFAX
/
file_handler.py
97 lines (89 loc) · 2.43 KB
/
file_handler.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
from os.path import join as _join
from os.path import expanduser as _expanduser
from os.path import dirname as _dirname
from os.path import realpath as _realpath
from os.path import isdir as _isdir
from os import mkdir as _mkdir
from os import getenv as _getenv
import json as _json
import pickle
if _getenv("SLAVE"):
default_path = _join(_expanduser("~"), ".slave/")
else:
default_path = _join(_expanduser("~"), ".klb/")
def test_dir(directory):
if not _isdir(directory):
try:
_mkdir(directory)
except:
pass
def open_local(f_name, method="r"):
try:
return open(_join(_expanduser("~"), ".klb/" + f_name),method)
except:
folder = _dirname(_realpath(__file__))
return open(_join(folder, "blank_file"))
def f_readlines(f_name):
ret = []
try:
with open(_join(_expanduser("~"), ".klb/" + f_name)) as f:
ret += f.readlines()
except:
pass
if _getenv("SLAVE"):
try:
with open(_join(_expanduser("~"), ".slave/" + f_name)) as f:
ret += f.readlines()
except:
pass
for i in range(len(ret)):
ret[i] = ret[i].strip("\n")
return ret
def f_read(f_name):
ret = ""
try:
with open(_join(_expanduser("~"), ".klb/" + f_name)) as f:
ret += f.read()
except:
pass
if _getenv("SLAVE"):
try:
with open(_join(_expanduser("~"), ".slave/" + f_name)) as f:
ret += f.read()
except:
pass
return ret
def f_read_json(f_name):
ret = {}
try:
with open(_join(_expanduser("~"), ".klb/" + f_name)) as f:
temp = _json.load(f)
for a in temp:
ret[a] = temp[a]
except:
pass
if _getenv("SLAVE"):
try:
with open(_join(_expanduser("~"), ".slave/" + f_name)) as f:
temp = _json.load(f)
for a in temp:
ret[a] = temp[a]
except:
pass
return ret
def f_read_pickle(f_name, path=None):
if path == None:
path = default_path
try:
with open(_join(path, f_name), "r") as f:
return pickle.load(f)
except:
pass
def f_write_pickle(f_name, var, path=None):
if path == None:
path = default_path
try:
with open(_join(path, f_name), "w") as f:
pickle.dump(var, f)
except:
pass