-
Notifications
You must be signed in to change notification settings - Fork 0
/
io_utils.py
155 lines (108 loc) · 2.7 KB
/
io_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
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 1 16:02:43 2019
@author: Samuele Garda
"""
import glob
import pickle
import logging
import json
logger = logging.getLogger(__name__)
logging.basicConfig(format = '%(asctime)s : %(levelname)s : %(module)s: %(message)s', level = 'INFO')
class IOManager:
"""
Class with IO helper functions
"""
@staticmethod
def files_in_folder(path,extension):
"""
Get all the files in a folder by extension, sorted.
Args:
path (str) : system path
extension (str) : file extensions (e.g. '.txt')
"""
return sorted(glob.iglob(glob.os.path.join(path,"*.{}".format(extension))))
@staticmethod
def remove_file(path):
"""
Delete file
Args:
path (str) : system path
"""
if glob.os.path.exists(path):
glob.os.remove(path)
@staticmethod
def base_name(path):
"""
Get base name of file (no full path)
Args:
path (str) : system path
"""
return glob.os.path.basename(path)
@staticmethod
def folder_name(path):
"""
Get folder name
Args:
path (str) : system path
"""
return glob.os.path.dirname(path)
@staticmethod
def check_exists(path):
"""
Check for file existance
Args:
path (str) : system path
"""
return glob.os.path.exists(path)
@staticmethod
def make_dir(path):
"""
Create folder (and subfolders if necessary)
Args:
path (str) : system path
"""
if not glob.os.path.exists(path):
glob.os.makedirs(path)
@staticmethod
def join_paths(paths):
"""
Create full path from list of elements
Args:
paths (list) : system paths
"""
return glob.os.path.join(*paths)
def load_json(path):
"""
Load JSON into dict
Args:
path (str) : system path
Return:
item (dict) : dictionary
"""
return json.load(open(path))
@staticmethod
def save_pickle(item,path):
"""
Save item in pickled format
Args:
item (whatever) : python object
path (str) : system path
"""
if not glob.os.path.exists(path):
pickle.dump( item, open( str(path), 'wb'))
else:
raise ValueError("File {} already exists! Not overwriting".format(path))
@staticmethod
def load_pickle(path):
"""
Load pickled object from file.
Args:
path (str) : system path
"""
if glob.os.path.exists(path):
item = pickle.load(open(str(path), mode = "rb"))
else:
raise ValueError("File {} not found!".format(path))
return item