gpt4 book ai didi

python - 如何在Python中从csv文件中提取行并将其复制到另一个csv文件?

转载 作者:太空宇宙 更新时间:2023-11-03 14:36:55 24 4
gpt4 key购买 nike

假设我的 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)

我试试

最佳答案

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

关于python - 如何在Python中从csv文件中提取行并将其复制到另一个csv文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46868555/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com