Python: Using a variable in a filename output [duplicate] - python

Sorry for this very basic question. I am new to Python and trying to write a script which can print the URL links. The IP addresses are stored in a file named list.txt. How should I use the variable in the link? Could you please help?
# cat list.txt
192.168.0.1
192.168.0.2
192.168.0.9
script:
import sys
import os
file = open('/home/list.txt', 'r')
for line in file.readlines():
source = line.strip('\n')
print source
link = "https://(source)/result”
print link
output:
192.168.0.1
192.168.0.2
192.168.0.9
https://(source)/result
Expected output:
192.168.0.1
192.168.0.2
192.168.0.9
https://192.168.0.1/result
https://192.168.0.2/result
https://192.168.0.9/result

You need to pass the actual variable, you can iterate over the file object so you don't need to use readlines and use with to open your files as it will close them automatically. You also need the print inside the loop if you want to see each line and str.rstrip() will remove any newlines from the end of each line:
with open('/home/list.txt') as f:
for ip in f:
print "https://{0}/result".format(ip.rstrip())
If you want to store all the links use a list comprehension:
with open('/home/list.txt' as f:
links = ["https://{0}/result".format(ip.rstrip()) for line in f]
For python 2.6 you have to pass the numeric index of a positional argument, i.e {0} using str.format .
You can also use names to pass to str.format:
with open('/home/list.txt') as f:
for ip in f:
print "https://{ip}/result".format(ip=ip.rstrip())

Get the link inside the loop, you are not appending data to it, you are assigning to it every time. Use something like this:
file = open('/home/list.txt', 'r')
for line in file.readlines():
source = line.strip('\n')
print source
link = "https://%s/result" %(source)
print link

Try this:
lines = [line.strip('\n') for line in file]
for source in lines:
print source
for source in lines:
link = "https://{}/result".format(source)
print link
The feature you just described is often called string interpolation.
In Python, this is called string formatting.
There are two styles of string formatting in Python: the old style and the new style.
What I've shown in the example above is the new style, in which we format with a string method named format.
While the old style uses the % operator, eg. "https://%s/result" % source

Use format specifier for string and also put the link printing section in the for loop only
something like this:
import sys
import os
file = open('/home/list.txt', 'r')
for line in file.readlines():
source = line.strip('\n')
print source
link = "https://%s/result”%source
print link

import sys
import os
file = open('/home/list.txt', 'r')
for line in file.readlines():
source = line.strip('\n')
print source
link = "https://" + str(source) + "/result”
print link

Related

How to check if a block of lines has a particular keyword using python?

I am checking a text file with blocks of commands as following -
File start -
!
interface Vlan100
description XYZ
ip vrf forwarding XYZ
ip address 10.208.56.62 255.255.255.192
!
interface Vlan101
description ABC
ip vrf forwarding ABC
ip address 10.208.55.126 255.255.255.192
no ip redirects
no ip unreachables
no ip proxy-arp
!
File End
and I want to create a txt file where if in source file I am getting a pattern vrf forwarding ABC output should be interface Vlan101
as of now what I have done following script but it showing only the line which contains the pattern.
import re
f = open("output_file.txt","w") #output file to be generated
shakes = open("input_file.txt","r") #input file to read
for lines in shakes:
if re.match("(.*)ABC(.*)",lines):
f.write(lines)
f.close()
Easiest: read the file, cut where ! is, then for each of those, if there's the desired text, get the first line:
with open("input_file.txt") as r, open("output_file.txt", "w") as w:
txt = r.read()
result = [block.strip().split("\n")[0]
for block in txt.split('!')
if 'vrf forwarding ABC' in block]
w.write("\n".join(result))
Just to be clear, I imagine that you want to replace any instances of "interface Vlan101" with "vrf forwarding ABC". In this case, I had test.txt as the input file and out.txt as the output file with all the replaced instances as was needed. I used a list comprehension--with a list string method-- to replace the substrings of "interface Vlan101" with "vrf forwarding ABC".
with open("test.txt") as f:
lines = f.readlines()
new_lines = [line.replace("interface Vlan101", "vrf forwarding ABC" for line in lines]
with open("out.txt", "w") as f1:
f1.writelines(new_lines)
Hope this helps.
If you are just interested in the interface, you can do following as well.
#Read File
with open('sample.txt', 'r') as f:
lines = f.readlines()
#Capture 'interfaces'
interfaces = [i for i in lines if i.strip().startswith('inter')]
#Write it to a file
with open('output.txt', 'w') as f:
f.writelines(interfaces)
With your code you are going through the document line by line.
If you want to parse blocks (between "!"-signs) you could split the blocks into lines first (though if it's a really large document, you may need to consider something else as this will read the entire document into memory)
import re
f = open("output_file.txt","w") #output file to be generated
source = open("input_file.txt","r") #input file to read
lines = "".join(source) #creates a string from the document
shakes = lines.replace("\n","").replace("! ","\n")
# remove all newlines and create new ones from "!"-block delimiter
# retrieve all text before "vrf forwarding ABC"
finds = re.findall("(.*)vrf forwarding ABC",shakes)
# return start of line
# if the part you want is the same length in all,
# then you could use find[:17] instead of
# find to get only the beginning. otherwise you need to modify your
# regex to only take the first 2 words of the line.
for find in finds:
f.write(find)
f.close()
Alternatively, if you want to use match per line, you can do the same as above, however instead of replacing "!" with new line, you can just split it, and then use the previous code and go line by line.
Hope this helps!

error in ip2location python library

I am using ip2location Python library to find out location of corresponding ip address.I am trying to open a file containing ip address list and find out corresponding location through that.
import IP2Location;
IP2LocObj = IP2Location.IP2Location();
IP2LocObj.open("data/IP-COUNTRY-REGION-CITY-. LATITUDE-LONGITUDE-ZIPCODE-TIMEZONE-ISP-DOMAIN-NETSPEED-AREACODE-WEATHER-MOBILE-ELEVATION-USAGETYPE-SAMPLE.BIN");//This is sample database
File1=open('test_ip.txt','r');//This is file containing ipaddress
Line=File1.readline();
While line:
rec = IP2LocObj.get_all(Line);
Line=File1.readline();
print rec.country_short
This code is giving error.You can check out the sample code here http://www.ip2location.com/developers/python
Please use the following Python codes.
import IP2Location;
IP2LocObj = IP2Location.IP2Location();
IP2LocObj.open("IP-COUNTRY-REGION-CITY-LATITUDE-LONGITUDE-ZIPCODE-TIMEZONE-ISP-DOMAIN-NETSPEED-AREACODE-WEATHER-MOBILE-ELEVATION-USAGETYPE-SAMPLE.BIN"); # This is sample database
with open('test_ip.txt') as f: # file containing ip addresses
for line_terminated in f:
line = line_terminated.rstrip('\r\n'); # strip newline
if line: # non-blank lines
print line
rec = IP2LocObj.get_all(line);
print rec.country_short

Python - Read value of variable from file

In bash, I have a file that stores my passwords in variable format.
e.g.
cat file.passwd
password1=EncryptedPassword1
password2=EncryptedPassword2
Now if I want to use the value of password1, this is all that I need to do in bash.
grep password1 file.passwd | cut -d'=' -f2
I am looking for an alternative for this in python. Is there any library that gives functionality to simply extract the value or do we have to do it manually
like below?
with open(file, 'r') as input:
for line in input:
if 'password1' in line:
re.findall(r'=(\w+)', line)
Read the file and add the check statement:
if line.startswith("password1"):
print re.findall(r'=(\w+)',line)
Code:
import re
with open(file,"r") as input:
lines = input.readlines()
for line in lines:
if line.startswith("password1"):
print re.findall(r'=(\w+)',line)
There's nothing wrong with what you've written. If you want to play code golf:
line = next(line for line in open(file, 'r') if 'password1' in line)
I found this module very useful ! Made life much easier.

How to open a file of different extension with notepad in python

I have a .fhx file that I could open normally with notepad but I want to open it using Python. I have tried subprocess.popen which I got online but I keep getting errors. I also want to be able to read the contents of this file like a normal text file like how we do in f=open("blah.txt", "r") and f.read(). Could anyone guide me in the right direction ?
import subprocess
filepath = "C:\Users\Ch\Desktop\FHX\fddd.fhx"
notePath = r'C:\Windows\System32\notepad.exe'
subprocess.Popen("%s %s" % (notePath, filepath))
Solved my problem by adding encoding="utf16" to the file open command.
count = 1
filename = r'C:\Users\Ch\Desktop\FHX\27-ESDC_CM02-2.fhx'
f = open(filename, "r", encoding="utf16") #Does not work without encoding
lines = f.read().splitlines()
for line in lines:
if "WIRE SOURCE" in line:
liner = line.split()
if any('SOURCE="INPUT' in s for s in liner):
print(str(count)+") ", "SERIAL INPUT = ", liner[2].replace("DESTINATION=", ""))
count += 1
Now I'm able to get the data the way I wanted.Thanks everyone.
try with shell=True argument
subprocess.call((notePath, filepath), shell=True )
You should be passing a list of args:
import subprocess
filepath = r"C:\Users\Ch\Desktop\FHX\fddd.fhx"
notePath = r'C:\Windows\System32\notepad.exe'
subprocess.check_call([notePath, filepath])
If you want to read the contents then just open the file using open:
with open(r"C:\Users\Ch\Desktop\FHX\fddd.fhx") as f:
for line in f:
print(line)
You need to use raw string for the path also to escape the f n your file path name, if you don't you are going to get errors.
In [1]: "C:\Users\Ch\Desktop\FHX\fddd.fhx"
Out[1]: 'C:\\Users\\Ch\\Desktop\\FHX\x0cddd.fhx'
In [2]: r"C:\Users\Ch\Desktop\FHX\fddd.fhx"
Out[2]: 'C:\\Users\\Ch\\Desktop\\FHX\\fddd.fhx'

Python 2.7 Loop through multiple subprocess.check_output calls

I am having an issue with printing output from subprocess.check_output calls.
I have a list of IP addresses in ip.txt that I read from and save to list ips.
I then iterate over that list and call wmic command to get some details from that machine, however only the last command called prints output. By looking at CLI output, I can see that print 'Complete\n' is called for each, but check_output is not returning anything to output variable.
Any ideas? Thanks
Python Code:
from subprocess import check_output
f_in = open('ip.txt', 'r')
ips = []
for ip in f_in:
ips.append(ip)
f_in.close()
f_out = open('pcs.txt','w')
for ip in ips:
cmd = 'wmic /node:%s computersystem get name,username' % (ip)
f_out.write('Trying %s\n'%ip)
print 'Trying: %s' % (ip)
try:
output = check_output(cmd,shell=True)
f_out.write(output)
print 'Output\n--------\n%s' % output
print 'Complete\n'
except:
f_out.write('Could not complete wmic call... \n\n')
print 'Failed\n'
f_out.close()
File Output:
Trying 172.16.5.133
Trying 172.16.5.135
Trying 172.16.5.98
Trying 172.16.5.131
Name UserName
DOMAINWS48 DOMAIN\staff
CLI Output
Trying: 172.16.5.133
Output
Complete
Trying: 172.16.5.135
Output
Complete
Trying: 172.16.5.98
Output
Complete
Trying: 172.16.5.131
Output
Name UserName
DOMAINWS48 DOMAIN\staff
Complete
In these lines you read a file line by line:
f_in = open('ip.txt', 'r')
ips = []
for ip in f_in:
ips.append(ip)
Unfortunately each line has an end of line character still terminating each line. You then pass the newline in as part of the IP address. You might want to consider stripping the newlines \n from the end of each line you read:
f_in = open('ip.txt', 'r')
ips = []
for ip in f_in:
ips.append(ip.strip('\n'))
strip('\n') will strip all the newlines from the beginning and end of the string. Information on this string method can be found in the Python documentation:
str.strip([chars])
Return a copy of the string with the leading and trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped:
You can also read all the lines from the file with something like:
ips = [line.strip('\n') for line in f_in.readlines()]
My guess is that your ip.txt file has an IP address on each line and the last line of the file is not terminated with a newline \n and in that case your code worked.

Categories

Resources