-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfile_helper.py
60 lines (53 loc) · 2 KB
/
file_helper.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
import json
import pickle # using pickle to store confirmation as set instead of dict
import os
import constants
def json_read(path: str) -> dict:
try:
with open(f"{path}", "r") as f:
data: dict = json.load(f)
except:
data = {}
return data
def json_write(path: str, data: dict) -> None:
while True:
try:
with open(f"{path}", "w+") as f:
json.dump(data, f)
backup(data, int(path.split("/")[-1].split("-")[0]), path.split("/")[-1].split("-")[1].split(".")[0])
break
except FileNotFoundError:
print("File not found, creating file...")
os.mkdir("/".join(path.split("/")[:-1]))
def pickle_read(path: str) -> set:
try:
with open(f"{path}", "rb") as f:
data: set = pickle.load(f)
except FileNotFoundError:
data = set()
return data
def pickle_write(path: str, data: set) -> None:
while True:
try:
with open(f"{path}", "wb+") as f:
pickle.dump(data, f)
break
except FileNotFoundError:
print("File not found, creating file...")
os.mkdir("/".join(path.split("/")[:-1]))
def backup(data: dict, id: int, msg: str) -> None:
# can you tell that copilot wrote most of this?
if not os.path.exists(constants.BACKUP_PATH):
os.mkdir(constants.BACKUP_PATH)
if not os.path.exists(f"{constants.BACKUP_PATH}/{id}"):
os.mkdir(f"{constants.BACKUP_PATH}/{id}")
files = os.listdir(f"{constants.BACKUP_PATH}/{id}")
files.sort(key=lambda x: int(x[7 + len(msg):-5]))
if len(files) >= constants.BACKUP_NUMBER:
os.remove(f"{constants.BACKUP_PATH}/{id}/{files[0]}")
try:
with open(f"{constants.BACKUP_PATH}/{id}/{msg}-backup{int(files[-1][7 + len(msg):-5]) + 1}.json", "w+") as f:
json.dump(data, f)
except IndexError:
with open(f"{constants.BACKUP_PATH}/{id}/{msg}-backup0.json", "w+") as f:
json.dump(data, f)