如何将类信息存储到表中并检索?
我正在解析一个文本文件(hosts.txt),它的格式如下:
#line to ignore
127.0.0.1,localhost
192.168.0.1,my gateway
8.8.8.8,google DNS
我的目标是读取每一行,把里面的两条信息存储到一个类里,然后把这个类放到一个表格中。
之后,我会遍历这个表格,读取每个“ip”和“desc”属性,然后对这个IP进行ping操作,并显示与这个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)
2 个回答
1
zeline=line.strip().split(',')
这段代码会创建一个字符串的列表。如果你想用“hosts[0].ip”来访问你的IP和描述信息,你需要按照这个格式来做:
ip, desc = line.strip().split(',')
hosts.append(dest(ip, desc))
现在这已经是一个对象的列表,而不是字符串了。
0
如果你只是用这个类来填充一个表格,那么使用数据类可能会更合适。
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]))