From 095f2e7affca551c102d7a3b55e4e12fcd2a3ab7 Mon Sep 17 00:00:00 2001 From: Utshant Gurung Date: Fri, 14 Aug 2026 15:30:33 -0400 Subject: [PATCH] fix: close JSON files with context managers --- API/Classes/Base/FileClass.py | 30 +++++++++++++----------------- 1 file changed, 13 insertions(+), 17 deletions(-) diff --git a/API/Classes/Base/FileClass.py b/API/Classes/Base/FileClass.py index 0bf61b3c..3cde9e4f 100644 --- a/API/Classes/Base/FileClass.py +++ b/API/Classes/Base/FileClass.py @@ -5,11 +5,10 @@ class File: @staticmethod def readFile(path): try: - f = open(path, mode="r") - data = json.loads(f.read()) + with open(path, mode="r") as f: + data = json.loads(f.read()) #cirilica u json file #data = json.load(open(path, encoding='utf-8-sig')) - f.close() return data except( IndexError): raise IndexError @@ -21,14 +20,13 @@ def readFile(path): @staticmethod def writeFile(data, path): try: - f = open(path, mode="w") - #json - #f.write(json.dumps(data, ensure_ascii=False, separators=(',', ':'))) - #f.write(json.dumps(data, ensure_ascii=True, indent=4, sort_keys=False)) - #ascii false da zapisemo cirilicu u file - f.write(json.dumps(data, ensure_ascii=True, indent=4, sort_keys=False)) + with open(path, mode="w") as f: + #json + #f.write(json.dumps(data, ensure_ascii=False, separators=(',', ':'))) + #f.write(json.dumps(data, ensure_ascii=True, indent=4, sort_keys=False)) + #ascii false da zapisemo cirilicu u file + f.write(json.dumps(data, ensure_ascii=True, indent=4, sort_keys=False)) #f.write(json.dumps(data)) - f.close() # except(IOError, IndexError): # return('File not found or file is empty') #ovako prosljedjujemo exception u prethodnom slucaju vracamo response u funkciju koja poziva writeFile @@ -44,10 +42,9 @@ def writeFile(data, path): @staticmethod def writeFileUJson(data, path): try: - f = open(path, mode="w") - #usjon - f.write(json.dumps(data)) - f.close() + with open(path, mode="w") as f: + #usjon + f.write(json.dumps(data)) except(IOError, IndexError): raise IndexError except OSError: @@ -56,9 +53,8 @@ def writeFileUJson(data, path): @staticmethod def readParamFile(path): try: - f = open(path, mode="r") - data = json.loads(f.read()) - f.close() + with open(path, mode="r") as f: + data = json.loads(f.read()) return data except( IndexError): raise IndexError