14
14
### incase people are using threadig, we lock file reads
15
15
lock = threading .Lock ()
16
16
17
+
17
18
### general file setup tools ###
18
19
19
20
def load_json_dict (filename , * args ):
@@ -27,7 +28,7 @@ def load_json_dict(filename, *args):
27
28
if not isinstance (data , dict ):
28
29
data = {}
29
30
except :
30
- pass # TODO: issue a warning and bubble it up
31
+ data = {} # TODO: issue a warning and bubble it up
31
32
lock .release ()
32
33
if args :
33
34
d = dict ()
@@ -41,15 +42,32 @@ def load_json_dict(filename, *args):
41
42
42
43
43
44
def save_json_dict (filename , json_dict ):
44
- """Will error if filename is not appropriate, but it's checked elsewhere.
45
- """
45
+ """Save json to file. Error if path DNE, not a dict, or invalid json."""
46
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 )
47
49
lock .acquire ()
48
50
with open (filename , "w" ) as f :
49
- f .write (json . dumps ( json_dict , indent = 4 ) )
51
+ f .write (json_string )
50
52
lock .release ()
51
53
else :
52
- 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 )
53
71
54
72
55
73
### Custom JSON encoders ###
0 commit comments