-
Notifications
You must be signed in to change notification settings - Fork 0
/
json_tools.py
54 lines (47 loc) · 1.62 KB
/
json_tools.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
#!/usr/bin/env python3
"""
Replay Mix+ by soreikomori
https://github.com/soreikomori/ReplayMixPlus
"""
import json
import logging
import os
logger = logging.getLogger('rpmplusLogger')
def writeIntoJson(content, filename):
"""
Writes into a .json file.
:param content: Whatever that is supposed to be written. In this program's context this is either a dict or a list.
:param filename: str with the json filename.
"""
with open(filename, 'w') as file:
logger.info("Wrote into " + filename)
json.dump(content, file)
def loadJson(filename):
"""
Loads a .json file.
:param filename: str with the json filename.
:return: Returns the loaded .json if the file was found and filled, an empty dictionary if the file was found but empty,
and None if the file was not found.
"""
try:
with open(filename, 'r') as file:
data = json.load(file)
if data:
return data
except FileNotFoundError:
logger.error("The file " + filename + " was not found.")
return None
except json.decoder.JSONDecodeError:
logger.error("The file " + filename + " was empty.")
return {}
def createJson(filename):
"""
Creates an empty .json file with the name given. If the file already exists, it does nothing.
:param filename: str with the json filename.
"""
if not os.path.exists(filename):
with open(filename, 'w') as json_file:
json.dump({}, json_file)
logger.info(filename + " created with empty dictionary.")
else:
logger.error(filename + " already exists.")