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)
If you are only using the class for populating a table, maybe a Dataclass will be a better fit.