-
Notifications
You must be signed in to change notification settings - Fork 1
/
file_manager.py
110 lines (91 loc) · 2.76 KB
/
file_manager.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
# System imports
import errno
import io
import json
import os
import sys
##############################
# BASIC OPERATIONS
##############################
# Saves string of text to a file
def save(path, data_str, mode='w'):
path = ensureAbsPath(path)
try:
with io.open(path, mode, encoding='utf-8') as f:
f.write(str(data_str))
except IOError:
# This block of code will run if the path points to a file in a
# non-existant directory. To fix this, create the necessary
# director(y/ies) and call this function again to create the file.
directory = os.path.dirname(path)
if not os.path.isdir(directory):
try:
os.makedirs(directory)
except OSError as oserr:
pass
if os.path.isdir(directory):
return save(path, data_str, mode)
else:
print('Could not write to ' + path)
return False
else:
return True
# Reads text from a file as a string and returns it
def read(path):
path = ensureAbsPath(path)
try:
return open(path, encoding="utf8").read()
except IOError:
print('Could not find or open file: ' + path)
return False
# Deletes the file at the specified path. Cryptic, I know.
def delete(path):
path = ensureAbsPath(path)
try:
os.remove(path)
except OSError:
print('Could not remove file: ' + path)
return False
else:
return True
# If any relative paths are given, make them relative to the bot's working dir
def ensureAbsPath(path):
botRootDir = os.path.dirname(os.path.abspath(sys.argv[0])) + '/'
return path if os.path.isabs(path) else botRootDir + path
##############################
# JSON FILES
##############################
# Converts object to JSON, then saves it to a file
def saveJson(path, data):
return save(
path,
json.dumps(
data,
ensure_ascii=False,
indent=4,
separators=(',', ': ')
)
)
# Reads text from a file, converts it to JSON, and returns it
def readJson(path):
f = read(path)
if f:
try:
return json.loads(f)
except ValueError:
print('Could not parse JSON file: ' + path)
return False
else:
return False
##############################
# MISC HELPER FUNCS
##############################
# Appends data to a file rather than overwriting it -- useful for logging
def append(path, data):
return save(path, data + '\n', 'a')
# Grabs the file contents and returns them, then deletes the file
# This is primarily used for the temporary logging mechanism
def readAndDelete(path):
fileContents = read(path)
delete(path)
return fileContents