从文件读取并存储到包含dict和lis的dict中

2024-06-26 00:07:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我在网上到处搜索我的问题的答案,我用我所学的知识来帮助我达到这一点。然而,我一直无法找到解决办法,让我在我需要的地方。你知道吗

以最短的方式,我需要创建一个包含字典和从文件中读取的值列表的字典,并打印输出。你知道吗

我可以使用静态创建的字典来实现这一点,但是在从文件读入时,我似乎无法以相同的格式创建字典。你知道吗

以下是我能够使用的代码:

routers = {'fre-agg1': {'interface Te0/1/0/0': ["rate-limit input 135", "rate-limit input 136"],
                        'interface Te0/2/0/0': ["rate-limit input 135", "rate-limit input 136"]},
           'fre-agg2': {'interface Te0/3/0/0': ["rate-limit input 135", "rate-limit input 136", "rate-limit input 137"]}}

for rname in routers:
    print rname
    for iname in routers[rname]:
        print iname
        for int_config in routers[rname][iname]:
            print int_config

它的输出完全按照我需要的格式打印:

fre-agg2
interface Te0/3/0/0
rate-limit input 135
rate-limit input 136
rate-limit input 137
fre-agg1
interface Te0/1/0/0
rate-limit input 135
rate-limit input 136
interface Te0/2/0/0
rate-limit input 135
rate-limit input 136

我尝试读取的文件的格式不同:

ama-coe:interface Loopback0
ama-coe: ip address 10.1.1.1 255.255.255.255
ama-coe:interface GigabitEthernet0/0/0
ama-coe: description EGM to xyz Gi2/0/1
ama-coe: ip address 10.2.1.1 255.255.255.254
ama-coe:interface GigabitEthernet0/0/1
ama-coe: description EGM to abc Gi0/0/1
ama-coe: ip address 10.3.1.1 255.255.255.254

对于这个文件,我希望文件的输出与上面显示的相同,接口配置列在接口名称下,设备名称下

ama-coe
interface Loopback0
ip address 10.1.1.1 255.255.255.255
interface GigabitEthernet0/0/0
etc etc etc

到目前为止,我的代码如下:

routers = {}

with open('cpe-interfaces-ipaddress.txt') as inputFile:
    inputData = inputFile.read().splitlines()
    for rname in inputData:
        device, stuff = rname.split(':')
        if not device in routers:
            routers[device] = None
        elif stuff == "interface":
            routers[device][None] = stuff

我知道这段代码非常不完整,但我一辈子都搞不懂字典和列表结构,就像静态创建dict时那样

如能提供任何帮助,我们将不胜感激。你知道吗

谢谢你。你知道吗


Tags: inipforinput字典rateaddressinterface
1条回答
网友
1楼 · 发布于 2024-06-26 00:07:25
routers = {}

with open('cpe-interfaces-ipaddress.txt') as inputFile:
    cur_interface = None
    for rname in inputFile:
        device, stuff = rname.strip().split(':')
        print device, stuff, cur_interface
        if not device in routers:
            routers[device] = {}

        if stuff.startswith("interface"):
            key_word, interface = stuff.split(' ')
            routers[device].setdefault(interface, [])
            cur_interface = interface
        else: # ip address
            routers[device][cur_interface].append(stuff)

不知道这是否符合你的需要。我假设每个ip地址都属于前一个接口。你知道吗

用字典整理东西的方法很常见。您应该学习一些内置方法,例如setdefaultappend。你知道吗

相关问题 更多 >