9
9
import json
10
10
import os .path
11
11
import sys
12
+ import threading
13
+
14
+ ### incase people are using threadig, we lock file reads
15
+ lock = threading .Lock ()
12
16
13
17
14
18
### general file setup tools ###
@@ -17,13 +21,15 @@ def load_json_dict(filename, *args):
17
21
"""Checks if file exists. Returns {} if something fails."""
18
22
data = {}
19
23
if os .path .exists (filename ):
24
+ lock .acquire ()
20
25
with open (filename , "r" ) as f :
21
26
try :
22
27
data = json .load (f )
23
28
if not isinstance (data , dict ):
24
29
data = {}
25
30
except :
26
- pass # TODO: issue a warning and bubble it up
31
+ data = {} # TODO: issue a warning and bubble it up
32
+ lock .release ()
27
33
if args :
28
34
d = dict ()
29
35
for key in args :
@@ -36,13 +42,32 @@ def load_json_dict(filename, *args):
36
42
37
43
38
44
def save_json_dict (filename , json_dict ):
39
- """Will error if filename is not appropriate, but it's checked elsewhere.
40
- """
45
+ """Save json to file. Error if path DNE, not a dict, or invalid json."""
41
46
if isinstance (json_dict , dict ):
47
+ # this will raise a TypeError if something goes wrong
48
+ json_string = json .dumps (json_dict , indent = 4 )
49
+ lock .acquire ()
42
50
with open (filename , "w" ) as f :
43
- f .write (json .dumps (json_dict , indent = 4 ))
51
+ f .write (json_string )
52
+ lock .release ()
44
53
else :
45
- raise TypeError ("json_dict was not a dictionay. couldn't save." )
54
+ raise TypeError ("json_dict was not a dictionary. not saving." )
55
+
56
+
57
+ def ensure_file_exists (filename ):
58
+ """Given a valid filename, make sure it exists (will create if DNE)."""
59
+ if not os .path .exists (filename ):
60
+ head , tail = os .path .split (filename )
61
+ ensure_dir_exists (head )
62
+ with open (filename , 'w' ) as f :
63
+ pass # just create the file
64
+
65
+
66
+ def ensure_dir_exists (directory ):
67
+ """Given a valid directory path, make sure it exists."""
68
+ if dir :
69
+ if not os .path .isdir (directory ):
70
+ os .makedirs (directory )
46
71
47
72
48
73
### Custom JSON encoders ###
0 commit comments