prompt_template/web/file_ops.py

58 lines
1.3 KiB
Python
Raw Normal View History

#!/usr/bin/env python3
"""
Datei-Ein-/Ausgabe-Operationen für Template-Dateien.
Stellt sichere Lese- und Schreiboperationen mit Encoding-Handling bereit.
"""
import os
from pathlib import Path
from typing import Optional
def read_file_binary(filepath: str) -> Optional[bytes]:
"""
Liest eine Datei im Binärmodus.
Args:
filepath: Absoluter Pfad zur Datei
Returns:
Dateiinhalt als Bytes, oder None bei Fehler
"""
try:
with open(filepath, "rb") as f:
return f.read()
except FileNotFoundError:
return None
except Exception:
return None
def write_file(filepath: str, content: bytes) -> bool:
"""
Schreibt Bytes in eine Datei. Erstellt parent-Verzeichnis falls nötig.
Args:
filepath: Absoluter Pfad zur Zieldatei
content: Zu schreibende Bytes
Returns:
True bei Erfolg, False bei Fehler
"""
try:
file_dir = os.path.dirname(filepath)
if not os.path.exists(file_dir) or not os.path.isdir(file_dir):
return False
with open(filepath, "wb") as f:
f.write(content)
return True
except Exception:
return False
def directory_exists(dirpath: str) -> bool:
"""Prüft, ob ein Verzeichnis existiert."""
return os.path.isdir(dirpath)