-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathutils.py
66 lines (56 loc) · 1.57 KB
/
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
import json
import os
import os.path as osp
import pickle as pkl
import pandas as pd
def set_gpu_devices(gpu_id):
gpu = ''
if gpu_id != -1:
gpu = str(gpu_id)
os.environ['CUDA_VOSIBLE_DEVICES'] = gpu
def load_file(filename):
"""
load obj from filename
:param filename:
:return:
"""
cont = None
if not osp.exists(filename):
print('{} not exist'.format(filename))
return cont
if osp.splitext(filename)[-1] == '.csv':
# return pd.read_csv(filename, delimiter= '\t', index_col=0)
return pd.read_csv(filename, delimiter=',')
with open(filename, 'r') as fp:
if osp.splitext(filename)[1] == '.txt':
cont = fp.readlines()
cont = [c.rstrip('\n') for c in cont]
elif osp.splitext(filename)[1] == '.json':
cont = json.load(fp)
return cont
def save_file(obj, filename):
"""
save obj to filename
:param obj:
:param filename:
:return:
"""
filepath = osp.dirname(filename)
if filepath != '' and not osp.exists(filepath):
os.makedirs(filepath)
else:
with open(filename, 'w') as fp:
json.dump(obj, fp, indent=4)
def pkload(file):
data = None
if osp.exists(file) and osp.getsize(file) > 0:
with open(file, 'rb') as fp:
data = pkl.load(fp)
# print('{} does not exist'.format(file))
return data
def pkdump(data, file):
dirname = osp.dirname(file)
if not osp.exists(dirname):
os.makedirs(dirname)
with open(file, 'wb') as fp:
pkl.dump(data, fp)