0

Estoy intentando leer varios archivos TXT. A los mismos les hago algunas modificaciones y luego los convierto en un DataFrame con Pandas y ahí también corro algunos procesos de modificación: hasta ahí todo bien, todo funciona perfecto, lo hago mediante un loop for, pero al momento de guardar el archivo xlsx y crear la primera hoja, no crea nuevas hojas, solo crea la primera.

El código es el siguiente:

from netmiko import ConnectHandler
from datetime import datetime
import re
from pathlib import Path
import os
import pandas as pd

ruta = Path("E:\Python\Visual Studio Code Proyects\M2M Real\Archivos")

def is_free(valor):
    color = 'green' if valor == "free"  else 'white'
    return 'background-color: %s' % color

list_txt = [ruta/"Router_a.txt", ruta/"Router_b.txt"]

for txt in list_txt:

  host = txt.stem

  sheet_name=f'{host}-Gi0-3-4-2'

  ruta_host = f'{ruta}\\interfaces.xlsx'

  df = pd.read_fwf(txt)

  df["Description"] = (df.iloc[:, 3:].fillna("").astype(str).apply(" ".join, axis=1).str.strip())

  df = df.iloc[:, :4]

  df = df.drop(columns = ["Status", "Protocol"])

  df.Interface = df.Interface.str.extract('Gi0/3/4/2\.(\d+)')

  df = df[df.Interface.notnull()].reset_index()

  df = df.drop(columns = ["index"])

  df['Interface'] = df['Interface'].astype(int)

  df = df.set_index('Interface').reindex(range(1,50)).fillna('free').reset_index()

  df = df.style.applymap(is_free)

  with pd.ExcelWriter(ruta_host, mode='a') as writer:

    df.to_excel(writer, sheet_name, index=False)

el formato del txt es el siguiente (vale aclarar que básicamente ambos txt de ambos router son casi idénticos):

Interface          Status      Protocol    Description
Gi0/3/4/2          up          up          ENLACE A Router_X
Gi0/3/4/2.5        up          up          Frontera Cliente A
Gi0/3/4/2.6        up          up          Frontera Cliente B
Gi0/3/4/2.7        up          up          Frontera Cliente C
Gi0/3/4/2.8        up          up          Frontera Cliente D
Gi0/3/4/2.9        up          up          Frontera Cliente E

¿Alguna idea de qué es lo que estoy haciendo mal?

1 respuesta 1

0

Pude resolver mi problema y aquí está el script:

from netmiko import ConnectHandler
from datetime import datetime
import re
from pathlib import Path
import os
import pandas as pd
from openpyxl import load_workbook

ruta = Path("E:\Python\Visual Studio Code Proyects\M2M Real\Archivos")

def is_free(valor):
    color = 'green' if valor == "free"  else 'white'
    return 'background-color: %s' % color

list_txt = [ruta/"FRUVI01.txt", ruta/"FRUVE01.txt"]

for txt in list_txt:

  with open(txt, "r") as f:

    lines = f.readlines()

  with open(txt, "w") as fw:
    for line in lines:

      if not re.match("-{5}|\s+|([A-Za-z0-9]+( [A-Za-z0-9]+)+)", line):
        fw.write(line)

for txt in list_txt:

  host = txt.stem

  sheet_name=f'{host}-Gi0-3-4-2'

  ruta_host = ruta/'ejemplo.xlsx'

  df = pd.read_fwf(txt)

  df["Description"] = (df.iloc[:, 3:].fillna("").astype(str).apply(" ".join, axis=1).str.strip())

  df = df.iloc[:, :4]

  df = df.drop(columns = ["Status", "Protocol"])

  df.Interface = df.Interface.str.extract('Gi0/3/4/2\.(\d+)')

  df = df[df.Interface.notnull()].reset_index()

  df = df.drop(columns = ["index"])

  df['Interface'] = df['Interface'].astype(int)

  df = df.set_index('Interface').reindex(range(1,3580)).fillna('free').reset_index()

  df = df.style.applymap(is_free)

  if not ruta_host.exists():
    writer = pd.ExcelWriter(ruta_host)
    writer.close()            
  else:
    pass  

  with pd.ExcelWriter(ruta_host, mode="a", engine="openpyxl", if_sheet_exists="overlay") as writer:

    df = df.to_excel(writer, sheet_name, index=False)

Debido a que tuve que crear un archivo y se generó con una hoja con el nombre "Sheet1", agregué el siguiente script para eliminarlo al final y fuera del ciclo:

wb = load_workbook(ruta_host)
if 'Sheet1' in wb.sheetnames:
  wb.remove(wb['Sheet1'])
  wb.save(ruta_host)
else:
  pass
1
  • No olvides aceptar tu respuesta cuando transcurra el tiempo mínimo.
    – padaleiana
    el 31 oct. 2022 a las 10:41

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.