Skip to content

Instantly share code, notes, and snippets.

@rnetonet
Created June 26, 2025 01:25
Show Gist options
  • Save rnetonet/28a3784a1c55caa77ec7bf29270e4b84 to your computer and use it in GitHub Desktop.
Save rnetonet/28a3784a1c55caa77ec7bf29270e4b84 to your computer and use it in GitHub Desktop.
"""
Script para ler arquivos XML de eventos eSocial e exportar os dados para um arquivo CSV.
"""
import csv
import xml.etree.ElementTree as ET
from dataclasses import dataclass, field
from pathlib import Path
@dataclass
class Evento:
nomeXml: str = field(default="")
perApur: str = field(default="")
cpf: str = field(default="")
nmTrab: str = field(default="")
matricula: str = field(default="")
dtNascto: str = field(default="")
codRubr: list[str] = field(default_factory=list)
vrRubr: list[str] = field(default_factory=list)
vrLiq: str = field(default="")
arquivos = [arquivo for arquivo in Path().iterdir() if arquivo.suffix.lower() == ".xml"]
def popular_evento_xml_recursivo(raiz, evento):
tag = raiz.tag.split("}", 1)[1]
campo = "cpf" if tag in ("cpfTrab", "cpfBenef") else tag
if hasattr(evento, campo) and raiz.text and raiz.text.strip():
if isinstance(getattr(evento, campo), list):
getattr(evento, campo).append(raiz.text.strip())
elif isinstance(getattr(evento, campo), str) and not getattr(evento, campo):
setattr(evento, campo, raiz.text.strip())
for elemento in raiz:
popular_evento_xml_recursivo(elemento, evento)
eventos = []
for arquivo in arquivos:
tree = ET.ElementTree(file=arquivo)
raiz = tree.getroot()
evento = Evento()
evento.nomeXml = arquivo.name
popular_evento_xml_recursivo(raiz, evento)
eventos.append(evento)
# Exportar para CSV
with open("export.csv", "w", newline="", encoding="utf-8") as csvfile:
writer = csv.writer(csvfile)
# Cabeçalho
writer.writerow(["nomeXml", "perApur", "cpf", "nmTrab", "matricula", "dtNascto", "codRubr", "vrRubr", "vrLiq"])
for evento in eventos:
writer.writerow(
[
evento.nomeXml,
evento.perApur,
evento.cpf,
evento.nmTrab,
evento.matricula,
evento.dtNascto,
", ".join(evento.codRubr),
", ".join(evento.vrRubr),
evento.vrLiq,
]
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment