Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Print items in list to variables

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading