I am trying to read several TXT files, I make some modifications to them and then I convert them into a DataFrame with Pandas and there I also run some modification processes, so far everything is fine, everything works perfect, I do it through a for loop but at the moment of save the xlsx file and create the first sheet and it doesn’t create new sheets, it just creates the first one.
the code is the following:
from netmiko import ConnectHandler
from datetime import datetime
import re
from pathlib import Path
import os
import pandas as pd
ruta = Path("E:PythonVisual Studio Code ProyectsM2M RealArchivos")
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)
the format of the txt is as follows, it is worth clarifying that basically both txt from both routers are almost identical:
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
Any idea what I’m doing wrong?
2
Answers
I was able to solve my problem and here is the script:
Because I had to create a create a file and it was generated with a sheet with the name "Sheet1", add the following script to delete it at the end and outside the loop:
move the line
outside the for loop for txt file.