M. Wolf M. Wolf - 5 months ago 9x
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


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
1          NaN            NaN
3          NaN            NaN

#Select only the rows where 'Wireless1' is not null
      Wired1         Wired2    Wireless1      Wireless2

#Select only 'Wireless' clolumn where it is not null
Name: Wireless1, dtype: object

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