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

50 Views Asked by At

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.

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)
2

There are 2 best solutions below

0
Sowmya On BEST ANSWER

If you are only using the class for populating a table, maybe a Dataclass will be a better fit.

from dataclasses import dataclass

@dataclass
class Dest:
     ip: str
     desc: str
     def __repr__(self):  # You can use the default __repr__ if it suits your usecase
          return f"{self.ip} ({self.desc})"

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(Dest(zeline[0], zeline[1]))
0
QuantumRifts On
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.