Verbessere Fehlerbehandlung und Dateikodierung in der get-Funktion

This commit is contained in:
2026-04-01 08:21:00 +02:00
parent 6bccca2864
commit b2959bebdb

View File

@@ -57,22 +57,14 @@ if file_suffix not in perm_file_suffix:
# Funktion zum Oeffnen einer Datei mit Pruefung
def get(name):
'''Funktion zum Oeffnen einer Datei mit Pruefung (prüft Encoding)'''
# Versuche zuerst UTF-8, lese einen kleinen Block zur Validierung.
# Versuche zuerst UTF-8, lese die gesamte Datei zur Validierung.
try:
f = open(name, "r", encoding='utf-8')
except IOError:
print("")
print("The File", name, "doesn't exist or can't be opened!")
print("")
sys.exit(1)
try:
# Lese ein kleines Stück, um mögliche Decode-Fehler sofort zu erzeugen
f.read(2048)
f.read() # komplette Datei lesen, um Decode-Fehler sicher zu erkennen
f.seek(0)
return f
except UnicodeDecodeError:
# UTF-8 scheint nicht zu passen — versuche ISO-8859-1
# UTF-8 passt nicht — versuche ISO-8859-1
try:
f.close()
return open(name, "r", encoding='ISO-8859-1')
@@ -81,9 +73,17 @@ def get(name):
print("The File", name, "can't be opened with fallback encoding!")
print("")
sys.exit(1)
except IOError:
print("")
print("The File", name, "doesn't exist or can't be opened!")
print("")
sys.exit(1)
except Exception:
# unerwarteter Fehler beim Lesen
try:
f.close()
except Exception:
pass
print("")
print("Error reading the file", name)
print("")