Traversing a file and splitting its contents into other separate files using Python

Asked

Viewed 106 times

0

from scapy.all import *

pkts = rdpcap("lalalao2.pcap")


#time slice de t em segundos : 10 minutos

t = 600
somaMin = pkts[0].time + t


valores=[]
for p in pkts:

    if p<=somaMin:

        valores.append(p)

    else:


        primslice =valores

        f=open("time1.txt",'w')
        f.writelines(primslice)

        valores=[]

        valores.append(p)

        somaMin=p.time + t

The above code opens a network dump file (PCAP) and creates vectors containing time Slices of t seconds. I would like each team Slice to be recorded in a different text file: time1, time2, ... The problem is that I do not know how many schools I will have, because it depends on the capture. It is possible?

1 answer

2


Yes, just make the file name variable. Something like open('time{}.txt'.format(i), 'w') where i is an accountant.

from scapy.all import *

pkts = rdpcap("lalalao2.pcap")

i = 1
# ^--- Inicia o contador

#time slice de t em segundos : 10 minutos

t = 600
somaMin = pkts[0].time + t

valores=[]
for p in pkts:

    if p<=somaMin:

        valores.append(p)

    else:

        primslice =valores

        f=open("time{}.txt".format(i),'w')
        #           ^--- Deixa o nome do arquivo variável

        f.writelines(primslice)

        i += 1
        # ^--- Incrementa o valor de i indefinidamente enquanto necessário

        valores=[]

        valores.append(p)

        somaMin=p.time + t

This code will generate the files time1.txt, time2.txt, time3.txt, etc..


Note: In your logic, if the number of Slices is not exactly a multiple of the time, you will lose the last Slice (it will not be written to file). Imagine that in each Cup 100 records will be recorded, but in the end, in the last Cup, there are no more than the exact 100, but only 90. When you loop, all records will enter if p<=somaMin, but none will enter the else, where the file is written. So I recommend that you turn the writing into a file into a function, call it inside the Else, if you still want, but after the is, check for elements in valores and if yes, call the function again.

  • about the note is just put what’s left out of the loop and write to another file

  • Which is exactly what I said, isn’t it?

  • @Anderson Carlos Woss, thank you. I will study the code here!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.