我有一个功能:
def devices():
devices = []
device = {}
with open('devices.txt', 'r') as file:
lines = file.readlines()
print(lines)
for line in lines:
device['ip'] = line.split(';')[0].strip()
device['name'] = line.split(';')[1].strip()
print(device)
devices.append(device)
print(devices)
return devices
devices.txt文件具有下一个布局:
1.1.1.1;device-1
2.2.2.2;device-2
当我在循环内打印设备字典时-可以。 但是作为回报,我得到了下一个列表:
[{'ip':'2.2.2.2', 'name':'device-2'},{'ip':'2.2.2.2', 'name':'device-2'}]
为什么?为什么不是该文件中的所有设备却只能运行2次?
答案 0 :(得分:0)
真的很有趣的问题!一开始我有点困惑,为什么它不起作用,然后我意识到循环外的dic。由于这些奇怪的问题,我通常不使用dic,在您的情况下,请在已附加变量的情况下更改它。这是您的代码的简单解决方案
def devices():
devices = []
with open('devices.txt', 'r') as file:
lines = file.readlines()
#print(lines)
for line in lines:
device = {}
device['ip'] = line.split(';')[0].strip()
device['name'] = line.split(';')[1].strip()
print(device)
devices.append(device)
print(devices)
((如果您想了解奇异的dic,可以在追加前写device = {}
一行,输出将是:
[{'ip':'2.2.2.2','name':'device-2'},{}]
{'ip':'2.2.2.2','name':'device-2'}如何到达那里,不知道)
答案 1 :(得分:-1)
def devices():
with open('devices.txt', 'r') as file:
return [{'ip':line.split(';')[0].strip(), 'name':line.split(';')[1].strip()} for line in file.readlines()]
print(devices())
# [{'name': 'device-1', 'ip': '1.1.1.1'}, {'name': 'device-2', 'ip': '2.2.2.2'}]