so i have a code like this :
hehe = 'ip.txt'
def ip(file):
with open(file, 'r') as list :
lists = list.read().splitlines()
ips = '\n'.join(map(str, lists))
for ip in ips:
ip1 = ip.rstrip('\n')
return ip1
list = ip(hehe)
print(list)
i have file of ips like :
- 1.1.1.1
- 2.2.2.2
- 3.3.3.3
I want to get every ip and scan it in next function / basiclly in reverse ip tool
when I execute my code I get only the last one !! my brain is dead today any help?
>Solution :
If you want the IPs stored in variables ip1, ip2, and so on. That is bad practice particularly when the number of IPs is large.
You are better off storing them in a dictionary (a container of key: value pairs) whereby the keys are 'ip1', 'ip2', and so on, and the values are the corresponding IPs.
However, ip1, ip2 and so on is not very meaningful. It is basically just the index of the IP in the file plus one. So a list is also well-suited for your problem.
The following shows how you might use a dict or list. We create the function myprint just to illustrate passing the dictionary, the list, or individual elements from the dictionary or list to a function.
With a dictionary, say, a, a['ip1'] is your first IP, a['ip2'] is your second IP, and so on.
With a list, say, b, b[0] is your first IP (ip1), b[1] is your second IP (ip2), and so on.
def ip2_dict(file):
with open(file) as f:
return {f"ip{idx+1}":line.rstrip() for idx, line in enumerate(f)}
def ip2_list(file):
with open(file) as f:
return [line.rstrip() for line in f]
def myprint(s):
print(s)
a = ip2_dict('ip.txt')
b = ip2_list('ip.txt')
# print dictionary of IPs
myprint(a)
# print list of IPs
myprint(b)
# print specific IP from dict
myprint(a['ip1'])
# print specific IP from list
myprint(b[0])
Output
{'ip1': '1.1.1.1', 'ip2': '2.2.2.2', 'ip3': '3.3.3.3'}
['1.1.1.1', '2.2.2.2', '3.3.3.3']
1.1.1.1
1.1.1.1