5a324f6554
Infra: cache_to_file, cache_to_sqlite, http_download_file, http_get_json, http_post_json, read_file_with_encoding, safe_extract_zip, scan_directory, setup_logger, normalize_zip_filenames. Tipos: 30+ tipos core (agent_action, context, task, message, parse_result...), 6 tipos datascience (entity_candidate, extraction_result...), 2 tipos infra. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
46 lines
1.4 KiB
Python
46 lines
1.4 KiB
Python
"""Lee un archivo de texto intentando multiples encodings en orden."""
|
|
|
|
from __future__ import annotations
|
|
|
|
|
|
def read_file_with_encoding(
|
|
path: str,
|
|
encodings: list[str] | None = None,
|
|
) -> str:
|
|
"""Lee un archivo de texto intentando multiples encodings en orden.
|
|
|
|
Intenta abrir el archivo con cada encoding de la lista hasta que
|
|
uno tenga exito. Util para archivos de origen desconocido (Windows,
|
|
Latin-1, archivos con BOM, etc.).
|
|
|
|
Args:
|
|
path: Ruta al archivo a leer.
|
|
encodings: Lista de encodings a intentar en orden. Por defecto
|
|
["utf-8", "utf-8-sig", "latin-1", "cp1252"].
|
|
|
|
Returns:
|
|
Contenido del archivo como string.
|
|
|
|
Raises:
|
|
ValueError: Si ningun encoding logra decodificar el archivo.
|
|
FileNotFoundError: Si el archivo no existe.
|
|
OSError: Si hay un error de I/O al abrir el archivo.
|
|
"""
|
|
if encodings is None:
|
|
encodings = ["utf-8", "utf-8-sig", "latin-1", "cp1252"]
|
|
|
|
last_error: UnicodeDecodeError | None = None
|
|
|
|
for encoding in encodings:
|
|
try:
|
|
with open(path, encoding=encoding) as fh:
|
|
return fh.read()
|
|
except UnicodeDecodeError as exc:
|
|
last_error = exc
|
|
continue
|
|
|
|
raise ValueError(
|
|
f"Unable to decode file '{path}' with encodings {encodings}. "
|
|
f"Last error: {last_error}"
|
|
)
|