Python脚本跳过行

时间:2017-04-10 15:41:30

标签: python csv

我希望自动执行以下过程,按照以下准则为特定系统分配特定的IP池: 1.跳过前10个IP 2.使用IP填充每个子网

我使用的是Python 3.5.1 我正在使用csv文件,这是我使用的数据样本:

  • Net STACK系统单元室
  • 10.0.28.0 CAB_DS4-2_2
  • 10.0.28.32 CAB_DS4-2_2
  • 10.0.28.64 CAB_DS4-1_1
  • 10.0.28.96 CAB_DS4-1_2
  • 10.0.28.128 CAB_DS3-2_1
  • 10.0.28.160 CAB_DS3-3_1
  • 10.0.28.192 CAB_DS3-3_2
  • 10.0.28.224 CAB_DS2-2_1

这是我制作的代码,它适用于正好一半的数据,在8个子网中,它只分配了4个。这是代码:

import csv
import ipaddress

with open('sorted2.csv') as csv_file:
    ip_pool = csv.reader(csv_file)
    next(ip_pool)

    for row in ip_pool:
        ip = ipaddress.ip_address(row[0])
        nextROW = next(ip_pool)
        ip_end = nextROW[0] #NEXT network limit
        counter = 0

        ip_end = ipaddress.ip_address(ip_end)
        ip_next = ip + 9 # skip first 10 IPs
        ip_assign = ipaddress.ip_address(ip_next)

        print ('NEW NET:', ip)
        while ipaddress.ip_address(ip_assign) < ipaddress.ip_address(ip_end)-1:
            counter += 1 # count number of IPs assigned, to be implemented later
            ip_assign = ipaddress.ip_address(ip_assign)+1 #iterate next IP
            ip_start = ip_assign

            print(ip_assign)
        ip_next = ip_assign

以下是代码的输出:

NEW NET: 10.0.28.0
10.0.28.10
10.0.28.11
10.0.28.12
10.0.28.13
10.0.28.14
10.0.28.15
10.0.28.16
10.0.28.17
10.0.28.18
10.0.28.19
10.0.28.20
10.0.28.21
10.0.28.22
10.0.28.23
10.0.28.24
10.0.28.25
10.0.28.26
10.0.28.27
10.0.28.28
10.0.28.29
10.0.28.30
10.0.28.31
NEW NET: 10.0.28.64
10.0.28.74
10.0.28.75
10.0.28.76
10.0.28.77
10.0.28.78
10.0.28.79
10.0.28.80
10.0.28.81
10.0.28.82
10.0.28.83
10.0.28.84
10.0.28.85
10.0.28.86
10.0.28.87
10.0.28.88
10.0.28.89
10.0.28.90
10.0.28.91
10.0.28.92
10.0.28.93
10.0.28.94
10.0.28.95
NEW NET: 10.0.28.128
10.0.28.138
10.0.28.139
10.0.28.140
10.0.28.141
10.0.28.142
10.0.28.143
10.0.28.144
10.0.28.145
10.0.28.146
10.0.28.147
10.0.28.148
10.0.28.149
10.0.28.150
10.0.28.151
10.0.28.152
10.0.28.153
10.0.28.154
10.0.28.155
10.0.28.156
10.0.28.157
10.0.28.158
10.0.28.159
NEW NET: 10.0.28.192
10.0.28.202
10.0.28.203
10.0.28.204
10.0.28.205
10.0.28.206
10.0.28.207
10.0.28.208
10.0.28.209
10.0.28.210
10.0.28.211
10.0.28.212
10.0.28.213
10.0.28.214
10.0.28.215
10.0.28.216
10.0.28.217
10.0.28.218
10.0.28.219
10.0.28.220
10.0.28.221
10.0.28.222
10.0.28.223

正如你所看到的,它跳过4个子网,我似乎无法将手指放在我编码错误/遗忘的地方。非常感谢任何帮助

1 个答案:

答案 0 :(得分:0)

在迭代它时,你不应该修改ip_pool

不是迭代行并尝试在迭代时获取下一行,而是跟踪上一行(我们仍然可以将其命名为row),但我们的迭代将在下一行而不是当前行上:

row = next(ip_pool)
for nextROW in ip_pool:
    ...
    row = nextROW