1

Let's suppose that I have a big data in a csv file:This is a set of lines from my file:

frame.number    frame.len   frame.cap_len   frame.Type  
  1               100           100           ICMP_tt   
  2                64            64           UDP   
  3               100           100           ICMP_tt   
  4                87            64           ICMP_nn

I want to extract 30 % from this file and put it in another csv file.

I try by using this code but it gives me selection per row not per line:

import csv

data = [] #Buffer list 
with open("E:\\Test.csv", "rb") as the_file:
    reader = csv.reader(the_file, delimiter=",")
    for line in reader:

        try:
            new_line = [line[0], line[1]]
            #Basically ´write the rows to a list
            data.append(new_line)
        except IndexError as e:
            print e
            pass

    with open("E:\\NewTest.csv", "w+") as to_file:
        writer = csv.writer(to_file, delimiter=",")
        for new_line in data:
            writer.writerow(new_line)

I try

1 Answer 1

1

Python csv module use , by default, so its not necessary to specify delimiter unless you have a different delimiter. I suppose you have following csv file:

frame.number,frame.len,frame.cap_len,frame.Type  
1,100,100,ICMP_tt
2,64,64,UDP
3,100,100,ICMP_tt
4,87,64,ICMP_nn

Each line in the file represents a row.

# read
data = []
with open('test.csv', 'r') as f:
    f_csv = csv.reader(f)
    # header = next(f_csv)
    for row in f_csv:
        data.append(row)


# write
with open('newtest.csv', 'w+') as f:
    writer = csv.writer(f)
    for i in range(int(len(data) * 30 / 100)):
        writer.writerow(data[i])
Sign up to request clarification or add additional context in comments.

2 Comments

thank you for you answer but i need to copy only 30% from my file
You can stop for loop when you get 30% of file. len(data) * 30 / 100) will give you 30% as line number.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.