I am currently work on a PCAP file and want to export of the one particular field(['TCP'].srcport) into a separate variable. The ['TCP'].srcport is not present for every row. it is present for the first 3 rows and not present for the remaining 3 row. The following is the code which I am using,
a = []
l = 0
for i in pcap_file:
try :
print l
print(i['TCP'].srcport)
a[l] = i['TCP'].srcport
l = l+1
except:
print l
print 'None'
a[l] = 0
l = l+1
continue
The problem here is the ['TCP'].srcport is not present in all the rows of the PCAP file. I want to parse the value wherever it is available and when it is not available, I want to give a value as "None". I am able to print something as follows,
64
64
64
None
None
None
But when I assign it to a variable, I am getting the following error,
--> 13 a[l] = "
14 l = l+1
15 continue
IndexError: list assignment index out of range
I would ideally want something like in a variable called l,
l
64 64 64 None None None
Can anybody help me in handling the exceptions and placing all the values into a variable?
Use a list comprehension with a conditional expression:
a = [i['TCP'] if 'TCP' in i else None for i in pcap_file]
Or use a .get()
call; it allows you to specify a default value to return, but the default for that is None
so there's no need to specify it.
a = [i.get('TCP') for i in pcap_file]