我有一个记事本,上面的数据是这样的:
10.0.0.1管理员管理员10.0.0.2管理员管理员10.0.0.3管理员
我想从记事本中获取这些数据,并将其导入python字典,其中键值为"ip":"10.0.0.1","name":"admin","passwd":"admin“,并通过循环将这些键值放入netmiko,以逐个连接每个设备。但是不知道如何将这些数据从记事本转换到字典:(
当前代码:
desktop = "C:\\Users\\Dawid\\Desktop\\"
with open(desktop+"devices.txt",'r') as file:
x = file.read().split()
for i in x:
var = {
'ip':i,
'name':'admin',
'passwd':'admin'
}
a = netmiko.ConnectHandler(**var)
发布于 2021-10-29 00:43:16
将文件读取到Python中,然后将其拆分成一个列表,然后将每个列表项拆分为一个字典:添加了文本文件行中缺少名称和密码的可能性,只留下IP作为可用变量。
dir = r"C:\Users\username\Desktop\"
with open(fr"{dir}file.txt", "r") as f:
a = f.read().splitlines()
a_list = [item.split(" ") for item in a]
for network in a_list:
if len(network) != 3:
network_dict = {"ip": network[0], "name": "default_name", "passwd": "default_password"}
else:
network_dict = {"ip": network[0], "name": network[1], "passwd": network[2]}
#do whatever is needed with the dict here
如果希望使用目录作为变量,请使用raw string
作为变量
dir = r"C:\Users\username\Desktop\"
这样,您就不必转义包括反斜杠在内的特殊字符。
发布于 2021-10-29 00:42:46
假设你的文件只有一行,并且你真正想要的是一个字典列表,这里有一个选项。
np = "10.0.0.1 admin admin 10.0.0.2 admin admin 10.0.0.3 admin admin"
tokens = np.split()
dicts = []
while tokens:
dicts.append({"pass": tokens.pop(), "user": tokens.pop(), "ip": tokens.pop()})
[print(d) for d in dicts]
让步:
➜ python np.py
{'pass': 'admin', 'user': 'admin', 'ip': '10.0.0.3'}
{'pass': 'admin', 'user': 'admin', 'ip': '10.0.0.2'}
{'pass': 'admin', 'user': 'admin', 'ip': '10.0.0.1'}
https://stackoverflow.com/questions/69765838
复制