Skip to content
Advertisement

Find Function in Python

I’ve made this code but it is not acting how I was expecting:

packets = rdpcap(file)
for m in packtes:
    if (raw(m)[14:].decode("ASCII")).find(search)!= -1:
        riga = (raw(m)[14:].decode("ASCII"))
        index_1 = riga[riga.index(":"):]      
        index_2 = index_1[1:index_1.index(",")]
        index_3 = index_2.replace(" ", "")
        if search == "True":
            var_1 = 1
        else:
            var_2 = 0
        break
    else:
        if test == "nothing":
            var_1 = 0
        else:
            var_2 = 1    

Basically I read a .pcap file which can be full of information or empty and I’m looking for a word inside each raw. If it is found I start some operation on this string in order to reach a desidered position inside the string.

I noticed that when the .pcap file is empty the code doesn’t enter into the “else” condition. I think I’m making a mistake with the find function in python but I don’t see it.

Advertisement

Answer

packets = rdpcap(file)
#gets executed when there's content in the file
if(packets):
    for m in packtes:
        if (raw(m)[14:].decode("ASCII")).find(search)!= -1:
            riga = (raw(m)[14:].decode("ASCII"))
            index_1 = riga[riga.index(":"):]      
            index_2 = index_1[1:index_1.index(",")]
            index_3 = index_2.replace(" ", "")
            if search == "True":
                var_1 = 1
            else:
                var_2 = 0
            break
        else:
            if test == "nothing":
                var_1 = 0
            else:
                var_2 = 1
else:
    print("Empty file")   

it will execute the outermost if statement when there’s content in the file otherwise it will execute the else statement.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement