我正在解析具有以下格式的文本文件(hosts.txt):
#line to ignore
127.0.0.1,localhost
192.168.0.1,my gateway
8.8.8.8,google DNS
我的目标是读取每一行,将这2条信息存储在一个类中,然后将该类存储在一个表中。
稍后,我将浏览该表,读取每个“ip”和“desc”属性,我将 ping IP ip 并显示与该 ip 相关的信息。
不幸的是,虽然
print(hosts[0])
工作得很好,但print(hosts[0].ip)
返回错误:
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'
我是否错误地将类存储在表中,或者错误地从中提取信息?
是否有更好的方法将这样的类存储在数据集中(可以不是表),以便在稍后阶段,我可以解析它并读取我需要的信息?
谢谢!
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)
zeline=line.strip().split(',')
这将创建一个字符串列表,如果您想使用“hosts[0].ip”访问您的 ip 和 desc,则需要遵循以下格式:
ip, desc = line.strip().split(',')
hosts.append(dest(ip, desc))
现在这是一个对象列表,而不是字符串。