From fe9d614a97a55e6e7b851f16eef4a4f2bd1dc5a7 Mon Sep 17 00:00:00 2001 From: LKuemmel Date: Mon, 8 Sep 2025 12:11:56 +0200 Subject: [PATCH 1/2] handle empty log file --- packages/control/chargelog/chargelog.py | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/packages/control/chargelog/chargelog.py b/packages/control/chargelog/chargelog.py index 4dcad2e8b2..992e261a8d 100644 --- a/packages/control/chargelog/chargelog.py +++ b/packages/control/chargelog/chargelog.py @@ -2,6 +2,7 @@ from enum import Enum import json import logging +import os import pathlib from typing import Any, Dict, List, Optional @@ -251,7 +252,13 @@ def write_new_entry(new_entry): (timecheck.create_timestamp_YYYYMM() + ".json")) try: with open(filepath, "r", encoding="utf-8") as json_file: - content = json.load(json_file) + try: + content = json.load(json_file) + except json.decoder.JSONDecodeError: + corrupt_path = filepath + ".bak1" + os.rename(filepath, corrupt_path) + log.error(f"ChargeLog: Korrupte Datei umbenannt nach {corrupt_path}") + content = [] except FileNotFoundError: # with open(filepath, "w", encoding="utf-8") as jsonFile: # json.dump([], jsonFile) From 86a5fc78c9f7c216f18712d720408f6e5412546a Mon Sep 17 00:00:00 2001 From: LKuemmel Date: Tue, 9 Sep 2025 11:51:19 +0200 Subject: [PATCH 2/2] review --- packages/control/chargelog/chargelog.py | 23 +++++++++++------------ 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/packages/control/chargelog/chargelog.py b/packages/control/chargelog/chargelog.py index 992e261a8d..b8605e058d 100644 --- a/packages/control/chargelog/chargelog.py +++ b/packages/control/chargelog/chargelog.py @@ -251,19 +251,18 @@ def write_new_entry(new_entry): filepath = str(_get_parent_file() / "data" / "charge_log" / (timecheck.create_timestamp_YYYYMM() + ".json")) try: - with open(filepath, "r", encoding="utf-8") as json_file: - try: - content = json.load(json_file) - except json.decoder.JSONDecodeError: - corrupt_path = filepath + ".bak1" - os.rename(filepath, corrupt_path) - log.error(f"ChargeLog: Korrupte Datei umbenannt nach {corrupt_path}") - content = [] + if os.path.exists(filepath) and os.path.getsize(filepath) == 0: + content = [] + else: + with open(filepath, "r", encoding="utf-8") as json_file: + try: + content = json.load(json_file) + except json.decoder.JSONDecodeError: + corrupt_path = f"{filepath}.unparsable_{timecheck.create_timestamp()}" + os.rename(filepath, corrupt_path) + log.error(f"ChargeLog: Korrupte Datei umbenannt nach {corrupt_path}") + content = [] except FileNotFoundError: - # with open(filepath, "w", encoding="utf-8") as jsonFile: - # json.dump([], jsonFile) - # with open(filepath, "r", encoding="utf-8") as jsonFile: - # content = json.load(jsonFile) content = [] content.append(new_entry) write_and_check(filepath, content)