forked from danielabler/label-map-warping
-
Notifications
You must be signed in to change notification settings - Fork 0
/
file_utils.py
53 lines (46 loc) · 1.57 KB
/
file_utils.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
import os
def get_file_extension(path_to_file):
"""
Returns file extension by splitting at '.' location, or None if no '.' in file name.
:param path_to_file: path to file to be tested
:return: string or None
"""
# need to sandbox for existence of '.'
# return None of component has no file extension
file_name = os.path.split(path_to_file)[-1]
file_name_split = file_name.split(".")
if file_name_split[-1] == file_name:
# there is no '.' in file_name
return None
else:
return file_name_split[-1]
def ensure_dir_exists(path):
"""
Checks whether path exists and creates main directory if not.
:param path: path to be tested
"""
if get_file_extension(path) == None:
# assume that 'path' is directory, add trailing '/'
path = path + '/'
if os.path.exists(os.path.dirname(path)):
return True
else:
try:
os.makedirs(os.path.dirname(path))
except:
pass
return False
def merge_dicts(a, b, path=None):
"merges b into a, from https://stackoverflow.com/questions/7204805/dictionaries-of-dictionaries-merge"
if path is None: path = []
for key in b:
if key in a:
if isinstance(a[key], dict) and isinstance(b[key], dict):
merge_dicts(a[key], b[key], path + [str(key)])
elif a[key] == b[key]:
pass # same leaf value
else:
raise Exception('Conflict at %s' % '.'.join(path + [str(key)]))
else:
a[key] = b[key]
return a