M. Wolf M. Wolf - 7 months ago 11
Python Question

Python netaddr throwing error when hitting empty csv cell

I have a static CSV document with the following headers

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


When searching for an IP, I look between the two wireless headers as well as the wired headers.

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


Now some entries have missing wireless ranges and/or missing wired ranges. I get the following error:

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


more specifically on the wireless header:

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


Now, I'm using Dictreader and from the documentation, isn't it supposed to skip empty lines? Is there another method that I could use to skip lines?

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


here's my variables if curious:

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


Example csv lines:

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

Answer

Consider using pandas, you can manipulate your csv file lot better.

import pandas as 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

Likewise you can do many more manipulations using pandas. Thus you can avoid null values being passed to netaddr.

Comments