Files
IPSExtractor/application/csv_manager.py
T

27 lines
947 B
Python

"""Gestor de escritura CSV.
Maneja la escritura incremental segura (con lock) en archivos CSV.
"""
import os
import csv
import threading
from typing import List, Dict, Any, Optional
class CSVManager:
def __init__(self):
self._lock = threading.Lock()
def append_rows(self, csv_path: str, rows: List[Dict[str, Any]], header: List[str]) -> None:
"""Anexa filas a un CSV, creando encabezado si el archivo no existe."""
os.makedirs(os.path.dirname(csv_path) or ".", exist_ok=True)
file_exists = os.path.exists(csv_path) and os.path.getsize(csv_path) > 0
with self._lock:
with open(csv_path, "a", encoding="utf-8", newline="") as f:
writer = csv.DictWriter(f, fieldnames=header, extrasaction="ignore", delimiter='|')
if not file_exists:
writer.writeheader()
for r in rows:
writer.writerow(r)