2016-04-26 46 views
1

時拋出的錯誤我有以下標題Python的netaddr中打空CSV細胞

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

當一個IP搜索,我的兩個無線頭,以及有線頭之間尋找一個靜態的CSV文件。

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 
+0

你可以添加幾行你正在閱讀的csv文件嗎? – Abbas

+0

增加了範圍,但出於安全原因,我保留了所有其他信息。 –

+0

在無法顯示實際值的地方添加虛擬值,將很容易重現您的問題併爲您提供幫助。 – Abbas

回答

1

考慮使用pandas,你可以操縱你的csv文件好多了。

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 

同樣可以用大熊貓做更多的操作。因此,您可以避免將空值傳遞給netaddr