Skip to content

Commit

Permalink
🩹 Simple fix for reading an empty file.
Browse files Browse the repository at this point in the history
  • Loading branch information
drawbu committed Feb 5, 2022
1 parent cb49a58 commit deb8d8f
Showing 1 changed file with 11 additions and 3 deletions.
14 changes: 11 additions & 3 deletions app/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
def json_wr(
filename: str,
mode: Literal["r", "w"] = "r",
data: Optional[JsonData] = {}
data=None
) -> Optional[JsonData]:
"""Write and read json files.
Expand All @@ -28,13 +28,21 @@ def json_wr(
Data of the file or default one if the mode is "r".
Nothing if the mode is "w".
"""
if data is None:
data = {}

filename = f"app/{filename}.json"

if mode == "r":
if not os.path.isfile(filename):
return data
with open(filename) as f:
return json.load(f)
try:
with open(filename) as f:
return json.load(f)
except json.decoder.JSONDecodeError:
with open(filename, "w") as f:
json.dump(data, f, indent=4)
return {}

elif mode == "w":
with open(filename, "w") as f:
Expand Down

0 comments on commit deb8d8f

Please sign in to comment.