简体   繁体   English

将IP地址列表导入数组/列表Python 2.7

[英]Importing list of IP addresses into array/list Python 2.7

I am working on a small project to take a list of IPs/subnet and convert them into separate IP address and subnet mask. 我正在做一个小项目,以获取IP /子网列表,并将它们转换为单独的IP地址和子网掩码。 I am using netaddr to complete the change and am now working on importing a list of IPs like below into and array or list. 我正在使用netaddr完成更改,现在正在努力将下面的IP列表导入到array和list中。

13.107.6.152/31 13.107.6.152/31

13.107.19.10/31 13.107.19.10/31

23.103.160.0/20 23.103.160.0/20

23.103.224.0/19 ...etc 23.103.224.0/19 ...等

I started in a txt file trying to import line by line, and have tried using a csv file with spaces delimited as well as putting commas and using that as the delimiter. 我从一个txt文件开始尝试逐行导入,并尝试使用带有空格分隔的csv文件以及放置逗号并将其用作分隔符。

This is my my most recent work using this as the csv file 这是我最近的工作,将其用作csv文件

    13.107.6.152/31,13.107.19.10/31,23.103.160.0/20


with open('FileLocation.csv', 'rb') as f:
reader = csv.reader(f, delimiter=',')
ipArray = list(reader)

However when I do: 但是,当我这样做时:

print len(ipArray)
print ipArray

It only returns 1 and then a block of the IP addresses. 它仅返回1,然后返回一个IP地址块。

Is there a better way to format the IPs in the csv or text file that will help me insert them into the array or list? 有没有更好的方法来格式化csv或文本文件中的IP,这将有助于我将其插入数组或列表中? My goal is to get each individual IP in its own spot so I can run it through a loop. 我的目标是使每个IP都处在自己的位置,这样我就可以循环运行它。

Thanks :) 谢谢 :)

With a txt file with 1 IP per line the following will accomplish what you need: 对于每行1个IP的txt文件,以下内容将满足您的要求:

with open('IPs.txt', 'r') as fin:
    ips = fin.read().splitlines()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM