I'm trying to convert from a txt file to another csv file but why can't do how can I need.
I got this txt:
Interface Status Protocol Description
Gi1 up up MANAGEMENT INTERFACE - DON'T TOUCH ME
Gi2 up up Network Interface
Gi2.101 up up mpls-subinterface-CKTx904949
Gi3 admin down down Network Interface
Lo0 up up
Lo56 up up THIS IS A TEST LOOPBACK
Vi0 up up
and this is my script:
output = open("command.txt", "r")
for line in output.readlines():
lista = re.sub(r'\s{2,}', ";", line)
archivo_csv = open("output-1.txt", "a")
archivo_csv.write(lista + ";" + "\n")
archivo_csv.close()
output.close()
output = open("output.txt", "r+") #This second "loop" is becose between "Protocol"
lineas = output.readlines() #and "Description" be only one space, the regular
linea_1 = lineas[0] #expression that i did don't work for this case
lista = re.sub(r'\s+', ";", linea_1)
output.seek(0)
output.write(lista)
output.close()
vaciar_archivo = open("output.csv", "w")
vaciar_archivo.close()
output = open("output.txt", "r")
for line in output.readlines():
lista = line
archivo_csv = open("output.csv", "a")
archivo_csv.write(lista)
archivo_csv.close()
output.close()
the output is this:
Interface;Status;Protocol;Description;
;
Gi1;up;up;MANAGEMENT INTERFACE - DON'T TOUCH ME
;
Gi2;up;up;Network Interface
;
Gi2.101;up;up;mpls-subinterface-CKTx904949
;
Gi3;admin down;down;Network Interface
;
Lo0;up;up;;
Lo56;up;up;THIS IS A TEST LOOPBACK
;
Vi0;up;up;;
i can't do this well, i think that i have a problem with the form of the regular expression.
I need this so that the CSV file does not generate blank lines:
Interface;Status;Protocol;Description
Gi1;up;up;MANAGEMENT INTERFACE - DON'T TOUCH ME
Gi2;up;up;Network Interface
Gi2.101;up;up;mpls-subinterface-CKTx904949
Gi3;admin down;down;Network Interface
Lo0;up;up
Lo56;up;up;THIS IS A TEST LOOPBACK
Vi0;up;up
Could you help me improve my code?
You can try pandas.read_fwf
:
import pandas as pd
df = pd.read_fwf("your_input_file.txt")
df["Description"] = (
df.iloc[:, 3:].fillna("").astype(str).apply(" ".join, axis=1).str.strip()
)
df = df.iloc[:, :4]
print(df)
df.to_csv("data.csv", index=False, sep=";")
Prints:
Interface Status Protocol Description
0 Gi1 up up MANAGEMENT INTERFACE - DON'T TOUCH ME
1 Gi2 up up Network Interface
2 Gi2.101 up up mpls-subinterface-CKTx904949
3 Gi3 admin down down Network Interface
4 Lo0 up up
5 Lo56 up up THIS IS A TEST LOOPBACK
6 Vi0 up up
and saves data.csv
:
Interface;Status;Protocol;Description
Gi1;up;up;MANAGEMENT INTERFACE - DON'T TOUCH ME
Gi2;up;up;Network Interface
Gi2.101;up;up;mpls-subinterface-CKTx904949
Gi3;admin down;down;Network Interface
Lo0;up;up;
Lo56;up;up;THIS IS A TEST LOOPBACK
Vi0;up;up;