51 lines
1.8 KiB
Python
Executable File
51 lines
1.8 KiB
Python
Executable File
#!/usr/bin/env python3
|
||
"""
|
||
Script: 02_prepara_per_trasmissione.py
|
||
Converte i CSV estratti in JSON e li copia/aggiorna nella cartella trasmissioni.
|
||
Prepara anche file DIFF se richiesto.
|
||
Autore: Pikappa2 – 2025-05-27
|
||
"""
|
||
|
||
import csv, json, os, hashlib, shutil
|
||
|
||
BASE = os.path.expanduser('~/netgescon')
|
||
ESTRATTI = os.path.join(BASE, 'estratti')
|
||
TRASM = os.path.join(BASE, 'trasmissioni')
|
||
LOG = os.path.join(BASE, 'log/preparazione_trasmissione.log')
|
||
os.makedirs(TRASM, exist_ok=True)
|
||
os.makedirs(os.path.dirname(LOG), exist_ok=True)
|
||
|
||
def hash_file(path):
|
||
h = hashlib.md5()
|
||
with open(path, 'rb') as f:
|
||
while True:
|
||
chunk = f.read(8192)
|
||
if not chunk:
|
||
break
|
||
h.update(chunk)
|
||
return h.hexdigest()
|
||
|
||
def csv_to_json(csv_path, json_path):
|
||
with open(csv_path, encoding='utf-8') as f:
|
||
reader = csv.DictReader(f)
|
||
data = list(reader)
|
||
with open(json_path, 'w', encoding='utf-8') as out:
|
||
json.dump(data, out, indent=2, ensure_ascii=False)
|
||
|
||
def main():
|
||
with open(LOG, 'a') as log:
|
||
log.write(f"==== {__import__('datetime').datetime.now()} - AVVIO PREPARAZIONE ====\n")
|
||
for root, dirs, files in os.walk(ESTRATTI):
|
||
for file in files:
|
||
if file.endswith('.csv'):
|
||
rel_dir = os.path.relpath(root, ESTRATTI)
|
||
out_dir = os.path.join(TRASM, rel_dir)
|
||
os.makedirs(out_dir, exist_ok=True)
|
||
csv_path = os.path.join(root, file)
|
||
json_path = os.path.join(out_dir, file.replace('.csv', '.json'))
|
||
csv_to_json(csv_path, json_path)
|
||
log.write(f"{csv_path} → {json_path} | hash {hash_file(json_path)}\n")
|
||
log.write(f"==== {__import__('datetime').datetime.now()} - FINE PREPARAZIONE ====\n")
|
||
|
||
if __name__ == "__main__":
|
||
main() |