如何从python中的csv文件中提取和复制行到另一个csv文件?

时间:2017-10-21 22:01:48

标签: python csv

我们假设我在csv文件中有一个大数据:这是我文件中的一组行:

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

我想从此文件中提取30%并将其放入另一个csv文件中。

我尝试使用此代码,但它让我选择每行不是每行:

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)

我试试

1 个答案:

答案 0 :(得分:1)

Python csv模块默认使用,,因此除非您有不同的分隔符,否则无需指定分隔符。我想你有以下csv文件:

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

文件中的每一行代表一行。

# 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])