gpt4 book ai didi

Python netaddr 在命中空 csv 单元格时抛出错误

转载 作者:太空宇宙 更新时间:2023-11-03 16:40:14 25 4
gpt4 key购买 nike

我有一个包含以下标题的静态 CSV 文档

City    State   Zip Latitude    Longitude   Subnet  Wired1  Wired2  Wireless1   Wireless2   Domain  Name    NAT_DHCP    NAT_Wireless

搜索 IP 时,我会查看两个无线 header 和有线 header 。

if (addr >= wired1 and addr <= wired2) or (addr >= wireless1 and addr <= wireless2):
print all header fields.

现在,某些条目缺少无线范围和/或缺少有线范围。我收到以下错误:

netaddr.core.AddrFormatError: failed to detect a valid IP address from ''

更具体地讲无线接头:

  File "script.py", line 175, in myfile
wireless1 = (int(IPAddress(row['Wireless1'])))

现在,我正在使用 Dictreader,并且从文档来看,它不是应该跳过空行吗?还有另一种方法可以用来跳过行吗?

with open('csvfiles/myfile.csv', 'rb') as incsv:
reader = csv.DictReader(incsv, delimiter=',')

如果好奇的话,这是我的变量:

addr = (int(IPAddress(ip)))
wired1 = (int(IPAddress(row['Wired1'])))
wired2 = (int(IPAddress(row['Wired2'])))
wireless1 = (int(IPAddress(row['Wireless1'])))
wireless2 = (int(IPAddress(row['Wireless2'])))

示例 csv 行:

Wired1      Wired2          Wireless1     Wireless2
10.65.0.0 10.65.239.255 10.65.240.1 10.65.255.254
10.38.0.0 10.38.239.255
10.34.0.0 10.34.239.255 10.34.240.1 10.34.255.254
10.83.0.0 10.83.239.255

最佳答案

考虑使用pandas ,您可以更好地操作 csv 文件。

将 pandas 导入为 pd

df = pd.read_csv('your_file.csv')

#See how does your data looks like in pandas
print df

Wired1 Wired2 Wireless1 Wireless2
0 10.65.0.0 10.65.239.255 10.65.240.1 10.65.255.254
1 10.38.0.0 10.38.239.255 NaN NaN
2 10.34.0.0 10.34.239.255 10.34.240.1 10.34.255.254
3 10.83.0.0 10.83.239.255 NaN NaN

#Select only the rows where 'Wireless1' is not null
df[pd.notnull(df['Wireless1'])]
Wired1 Wired2 Wireless1 Wireless2
0 10.65.0.0 10.65.239.255 10.65.240.1 10.65.255.254
2 10.34.0.0 10.34.239.255 10.34.240.1 10.34.255.254

#Select only 'Wireless' clolumn where it is not null
df[pd.notnull(df['Wireless1'])]['Wireless1']
0 10.65.240.1
2 10.34.240.1
Name: Wireless1, dtype: object

同样,您可以使用 pandas 进行更多操作。因此,您可以避免将空值传递给 netaddr

关于Python netaddr 在命中空 csv 单元格时抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36871722/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com