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;
Related
I have created a Python script that replaces text and adds quotes to characters from a text file. I would like to remove any other surrounding lines of text, which usually starts with the word "set".
Here is my current code:
import re
with open("SanitizedFinal_E4300.txt", "rt") as fin:
with open("output6.txt", "wt") as fout:
for line in fin:
line = line.replace('set system host-name EX4300', 'hostname "EX4300"')
line = line.replace('set interfaces ge-0/0/0 unit 0 family inet address', 'ip address')
line = re.sub(r'set interfaces ge-0/0/0 description (.*)', r'interface 1/1\nname "\1"', line)
line = re.sub(r'set interfaces ge-0/0/1 description (.*)', r'interface 1/2\nname "\1"', line)
#and so on...
fout.write(line)
The source text file contains surrounding text like this:
set system auto-snapshot
set system domain-name EX4300.lab
set system time-zone America/New_York
set system no-redirects
set system internet-options icmpv4-rate-limit packet-rate 2000
set system authentication-order tacplus
set system ports console type vt100
I would like to remove any other text that I have not called for in the code.
I have tried adding this to the bottom of my code with no success:
for aline in fin:
new_data = aline
if new_data.startswith("set"):
new_data = ""
What I would do is read the file, create a string with all of the info, then write it to a different file. It would go something like this:
import re
with open("SanitizedFinal_E4300.txt", "r") as f:
read = f.read()
info = ""
for line in read.split("\n"):
og_line = line
line = line.replace('set system host-name EX4300', 'hostname "EX4300"')
line = line.replace('set interfaces ge-0/0/0 unit 0 family inet address', 'ip address')
line = re.sub(r'set interfaces ge-0/0/0 description (.*)', r'interface 1/1\nname "\1"', line)
line = re.sub(r'set interfaces ge-0/0/1 description (.*)', r'interface 1/2\nname "\1"', line)
if "set" in line and line == og_line: # line == og_line makes sure that "line" wasn't changed at all
line = ""
if line != "":
info += line + "\n"
with open("output6.txt", "w+") as f:
f.write(info)
I currently have this code to read a .CSV file, and SSH into a router with the hostname/IP listed on the .CSV
The problem is that the file reads the line as "192.168.2.1/r/n"
Example: ('Node', 4, '...Checking IP Address...', 'CPE-SIBFOPASO-103179-01\r\n')
Can you please help?
Code Sample:
nodenum=1
f=open('Routers.csv', 'r') #Ficheiro com Hostnames
c=f.readlines()
with open('Output.csv','wb') as f: #Ficheiro novo com o output
write = csv.writer(f)
write.writerow(['Hostname', "Cellular"])
for i in c :
print ("Node", nodenum, "...Checking IP Address...", i)
try:
Connection = netmiko.ConnectHandler(ip=i, device_type="cisco_ios" , username="y", password="x", verbose=Fal
se)
Ended up achieving the result I wanted by changing the code to this:
f=open('Routers.csv', 'r')
c=f.read()
file_as_list = c.splitlines()
I am trying to write system info to a spreadsheet. but when I try to use my variables they come out black
import csv
import os
import linecache
os.system('getmac -v > mac.txt')
os.system("wmic bios get serialnumber > serial.txt")
os.system("wmic computersystem get model > model.txt")
os.system("hostname > hostname.txt")
os.system("ipconfig > ip.txt")
open('ip1.txt','w').writelines([line for line in open('ip.txt')if 'IPv4' in line])
open('mac1.txt','w').writelines([line for line in open('mac.txt')if 'Wi-Fi' in line])
open('mac2.txt','w').writelines([line for line in open('mac.txt')if 'Ethernet' in line])
serial = linecache.getline('serial.txt', 3)
model = linecache.getline('model.txt', 3)
mac = open("mac.txt","r")
IP = open("ip1.txt","r")
mac1 = open("mac1.txt","r")
mac2 = open("mac2.txt","r")
hostname = open("hostname.txt","r")
Rmac = mac.read()
Rip = IP.read()
Rmac1 = mac1.read()
Rmac2 = mac2.read()
Rhostname = hostname.read()
myData = [[model]]
myFile = open('example2.csv', 'w')
with myFile:
writer = csv.writer(myFile)
writer.writerows(myData)
this just will not write the information to the spreadsheet? what am I doing wrong? I am very new to programming btw
You don't need intermediary files, why not call your commands and write their info to your CSV immediately without all that back and forward dancing?
import csv
import subprocess
# get the model
model = subprocess.check_output(["WMIC", "computersystem", "get", "model"],
universal_newlines=True).strip().rsplit("\n", 1)[1]
# get the serial
serial = subprocess.check_output(["WMIC", "bios", "get", "serialnumber"],
universal_newlines=True).strip().rsplit("\n", 1)[1]
# get the host name
hostname = subprocess.check_output(["hostname"], universal_newlines=True).strip()
# get WMI output for all addresses
ips = subprocess.check_output(["WMIC", "NICCONFIG", "where", "IPEnabled=true",
"get", "IPAddress"],
universal_newlines=True).strip().split("\n\n")[1:]
# post-process to get the addresses only
ips = [ip.split(",")[0].strip('"{} ') for ip in ips]
# etc.
with open("example2.csv", "wb") as f: # open your CSV for writing
writer = csv.writer(f) # create a writer
# you didn't write a header but let's add it in
writer.writerow(["model", "serial", "hostname", "ips"]) # etc., you get the picture...
writer.writerow([model, serial, hostname, ",".join(ips)]) # add other columns, too
And you'll get a nice example2.csv containing:
model,serial,hostname,ips
Your Model,Your Serial,Your-Hostname,List.Of.IP.Addresses
Do the same for the other fields and you're done.
My requirement is to open a properties file and update the file, for update purpose i need to search for a specific string which stores the url information. For this purpose i have written the below code in python:
import os
owsURL="https://XXXXXXXXXXXXXX/"
reowsURL = "gStrOwsEnv = " + owsURL + "/" + "OWS_WS_51" + "/"
fileName='C:/Users/XXXXXXXXXXX/tempconf.properties'
if not os.path.isfile(fileName):
print("!!! Message : Configuraiton.properties file is not present ")
else:
print("+++ Message : Located the configuration.properties file")
with open(fileName) as f:
data = f.readlines()
for m in data:
if m.startswith("gStrOwsEnv"):
print("ok11")
m = m.replace(m,reowsURL)
after executing the program i am not able to update the properties file.
Any help is highly appreciated
Sample Content of file:
# ***********************************************
# Test Environment Details
# ***********************************************
# Application URL pointing to test execution
#gStrApplicationURL =XXXXXXXXXXXXXXXX/webservices/person
#gStrApplicationURL = XXXXXXXXXXXXXX/GuestAPIService/ProxyServices/
# FOR JSON
#gStrApplicationURL = XXXXXXXXXXXXXX
#SOAP_gStrApplicationURL =XXXXXXXXXXXXXXXXXXXXXXX
#(FOR WSDL PARSING)
version = 5
#v9
#SOAP_gStrApplicationURL = XXXXXXXXXXX/XXXXXXXXX/XXXXXXXXX/
#v5
SOAP_gStrApplicationURL = XXXXXXXXXXXXXXX/OWS_WS_51/
gStrApplicationXAIServerPath=
gStrEnvironmentName=XXXXXXXXX
gStrOwsEnv = XXXXXXXXXXXXXXXXXXXX/OWS_WS_51/
gStrConnectEnv = XXXXXXXXXXXXXXXXX/OWSServices/Proxy/
gStrSubscriptionKey =XXXXXXXXXXXXXXXXXXXXXX
I'm pretty sure that this is not the best way of doing that, but this is still one way:
with open(input_file_name, 'r') as f_in, open(output_file_name, 'w') as f_out:
for line in f_in:
if line.startswith("gStrOwsEnv"):
f_out.write(reowsURL)
else:
f_out.write(line)
That script copy every line of input_file_name into output_file_name except the lines that you want to change.
i am newbie to python. I am trying to parse a file to extract certain columns and write to an output file. I was able to parse and extract the desired columns but having trouble writing them to an output file.
Here is the original test file:
EGW05759 Pld5 I79_005987 GO_function: GO:0003824 - catalytic activity [Evidence IEA]; GO_process: GO:0008152 - metabolic process [Evidence IEA]
EGW05760 Exo1 I79_005988 GO_function: GO:0003677 - DNA binding [Evidence IEA]; GO_function: GO:0003824 - catalytic activity [Evidence IEA]; GO_function: GO:0004518 - nuclease activity [Evidence IEA]; GO_process: GO:0006281 - DNA repair [Evidence IEA]
Here is my python code
f = open('test_parsing.txt', 'rU')
f1 = open('test_parsing_out.txt', 'a')
for line in f:
match = re.search('\w+\s+(\w+)\s+\w+\s+\w+\:', line)
match1 = re.findall('GO:\d+', line)
f1.write(match.group(1), match1)
f1.close()
Basically i want the output to look like this (though i know my code is not complete to achieve this)
Pld5 GO:0003824:GO:0008152
Exo1 GO:0003677:GO:0003824:GO:0004518:GO:0006281
Thanks
Upendra
f = open('test_parsing.txt', 'rU')
f1 = open('test_parsing_out.txt', 'a')
for line in f:
match = re.search('\w+\s+(\w+)\s+\w+\s+\w+\:', line)
match1 = re.findall('GO:\d+', line)
f1.write('%s %s \n'%(match.group(1), ''.join(match1)))
f1.close()
Using the csv module:
import csv, re
with open('test_parsing.txt', 'rU') as infile, open('test_parsing_out.txt', 'a') as outfile:
reader = csv.reader(infile, delimiter="\t")
for line in reader:
result = line[1] + " " + ':'.join(re.findall("GO:\d{6}", line[3]))
outfile.write(result + "\n")
# OUTPUT
Pld5 GO:000382:GO:000815
Exo1 GO:000367:GO:000382:GO:000451:GO:000628