Python:比较CSV文件中IP地址的有效方法 [英] Python: Efficient way to compare ip addresses in a csv file

查看:109
本文介绍了Python:比较CSV文件中IP地址的有效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个csv文件,其中包含以下ip地址的列表:

I have a csv file which has the list of the following ip addresses:

SSH IP                NFS IP                iSCSI IP
10.xxx.xxx.aaa        172.xxx.xxx.aaa       172.yyy.xxx.aaa
10.xxx.xxx.bbb        172.xxx.xxx.bbb       172.yyy.xxx.bbb
10.xxx.xxx.ccc        172.xxx.xxx.ccc       172.yyy.xxx.ccc
10.xxx.xxx.ddd        172.xxx.xxx.ddd       172.yyy.xxx.ddd
...                   ...                   ...
...                   ...                   ...

我想比较SSH IP,NFS IP和iSCSI IP中的最后一个八位位组,如果它们匹配,我想通过在框中单击来执行一些命令。

I want to compare the last octets in SSH IP, NFS IP and iSCSI IP and if they match, i want to execute a few commands, by ssh'ing into the box.

考虑到我的情况,我想知道比较最后八位字节的最有效方法。

I want to know the most efficient way to compare the last octets, considering my case. Any help around this would be highly appreciated.

P.S。我没有任何问题,我打算使用paramiko库。

P.S. I do not have any problems in ssh'ing into the box, i am planning to use the paramiko library.

推荐答案

一个简单的方法一种方式是使用Python CSV库一次一次导入数据。然后使用列表推导将IP地址拆分为多个组件,获取最后一个并将其添加到集合中。如果集合的长度为1,则您知道所有列都是相同的。

One simple way would be to use the Python CSV library to import the data a row at a time. Then to use a list comprehension to split the IP address into components, taking the last one and adding it to a set. If the set results in a length of 1, you know all columns are the same.

我假设以上数据显示的是CSV文件,并且以制表符分隔: / p>

I am assuming the above data shows the CSV file, and is tab delimited:

import csv

reader = csv.reader(open(r"addresses.csv", "rb"), delimiter="\t")

for lCols in reader:
    try:
        if len(set([szIP.split(".")[3] for szIP in lCols])) == 1:
            print "\t".join(lCols)
    except:
        pass     # Skip non IP address formatted rows

如果您正在寻找最快的解决方案,我强烈建议您根据此代码安排任何正则表达式解决方案的时间,以确定哪个是

If you are looking for the fastest solution, I strongly suggest you time any regular expression solution against this code to determine which is the best, as it not always obvious which would be best.

如果您的CSV文件采用其他格式,则只需执行一个附加的列表理解步骤即可将其转换为上面的数据显示方式。

If your CSV file is in a different format, it would simply need an additional list comprehension step to convert it to how the data is shown above.

这篇关于Python:比较CSV文件中IP地址的有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆