-
Notifications
You must be signed in to change notification settings - Fork 0
/
myfile.py
42 lines (31 loc) · 894 Bytes
/
myfile.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
import myjson
import os
def to_file(file_name, text):
try:
os.remove(file_name)
except FileNotFoundError as e:
pass
if isinstance(text, str):
mode = 'wt'
else:
mode = 'wb'
with open(file_name, mode) as f:
try:
f.write(text)
finally:
f.close()
def from_file(file_name):
with open(file_name, 'rb') as f:
return f.read()
def txt_from_file(file_name):
with open(file_name, 'r') as f:
return f.read()
def json_from_file(file_name, err_msg=None):
data = None
with open(file_name, 'rb') as f:
data = myjson.json.load(f)
if not data:
raise Exception(err_msg if err_msg else "No data loaded.")
return data
def json_to_file(file_name, data):
to_file(file_name, myjson.json.dumps(data, ensure_ascii=False, indent=2, cls=myjson.MYJSONEncoder))