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

How to store/retrieve a class information to/from a table?

I’m parsing a text file (hosts.txt) that has the following format:

#line to ignore
127.0.0.1,localhost
192.168.0.1,my gateway
8.8.8.8,google DNS

My goal is to read each line, store the 2 pieces of information in a class, and then store the class in a table.

Later on, I will go through the table, will read each "ip" and "desc" attribute, I will ping the IP ip and display the info related to that ip.

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

Unfortunately, while print(hosts[0]) nicely works, print(hosts[0].ip) returns an error:

Traceback (most recent call last):
  File "/home/gda/bin/python/classes/draft.py", line 25, in <module>
    print(hosts[0].ip)
          ^^^^^^^^^^^
AttributeError: 'list' object has no attribute 'ip'

Am I wrongly storing the class in my table, or wrongly extracting the info from it?

Is there a better way to store such a class in a dataset (can be other than a table) so that at a later stage, I can parse it and read the info I need?

Thank you!

hosts = []

class dest:
  def __init__(self, ip, desc):
    self.ip = ip
    self.desc = desc
  def __str__(self):
    return f"{self.ip} ({self.desc})"

#INIT: Read hosts.txt and populate list hosts[]
with open('hosts.txt','r') as f:
     while True:
          line = f.readline()
          if not line: #Stop at end of file
               break
          if not line.startswith("#"):
               zeline=line.strip().split(',') #strip() removes the ending carriage return
               hosts.append(zeline)
f.close()
print(hosts[0].ip)

>Solution :

zeline=line.strip().split(',')

this will create a list of strings, and if you want to access to your ip and desc using this "hosts[0].ip", you’ll need to follow this format :

ip, desc = line.strip().split(',')
hosts.append(dest(ip, desc))

now this is a list of objects and not strings.

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