从具有多列的txt文件中分配数据

2024-05-14 19:24:57 发布

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

嗨,我有一个txt文件,它有两列(中间有空格),例如:

IP1 MAC1
IP2 MAC2
IP3 MAC3

以此类推(这些将是实际的IP地址和MAC地址)

我需要一个知道IP1和MAC1在一条线上并且相关的循环的帮助

我正在尝试编写一个程序,它使用循环,使用第一列文本(ip地址),登录到交换机,并使用第二列值(MAC地址)来分配MAC in端口安全性。然后它转到下一行,得到第二个IP和MAC,并执行相同的操作,依此类推,直到文件结束

我有登录和命令设置,但我有问题,从文本和循环获取数据,使IP1知道它需要有MAC1


Tags: 文件文本程序iptxtmac地址交换机
3条回答

希望这能为您提供另一种方法:

import pandas as pd
filename =r'c:\temp\input.txt'
list =  pd.read_csv(filename, sep=' ', skiprows=0, header=None).fillna('')
for i, row in list.iterrows():
    print '-'.join(p for p in row)

Output
IP1-MAC1
IP2-MAC2
IP3-MAC3

为了让你开始,我举个例子。在名为“file.txt”的文件中用空格分隔ip和MAC,可以运行以下代码:

with open('file.txt') as input_file:
    for i, line in enumerate(input_file):
        line = line.strip()
        ip, mac = line.split()
        print("ip: " + ip + ", mac: " + mac)

将输出以下内容:

ip: IP1, mac: MAC1
ip: IP2, mac: MAC2
ip: IP3, mac: MAC3

不过,我同意斯科特·亨特的观点,你似乎没有试图自己解决这个问题,这是令人惊讶的,因为你对IPs和MACs的技术术语是你可以在谷歌上找到答案的证据(我就是这么做的)

#Open the file and make a list of tuples [(ip1, mac1), (ip2, mac2)..]

txt_file = open("text.txt", "r")
x = [x.rstrip().split() for x in file.readlines()]

#now make a dictionary where key = ip, v = MAC
dict_ = {k: v for k, v in x}

# You now have a dictionary where you can get the MAC from ip via
>>>dict_['ip address'] 
>>>MAC

希望有帮助

相关问题 更多 >

    热门问题