在新csv fi中复制值

2024-09-30 18:15:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个程序,希望将结果写入一个逗号分隔的文件,如CSV

 new_throughput =[]
 self.t._interval = 2
 self.f = open("output.%s.csv"%postfix, "w")
 self.f.write("time, Byte_Count, Throughput \n")
 cur_throughput = stat.byte_count  
 t_put.append(cur_throughput)
 b_count = (cur_throughput/131072.0) #calculating bits
 b_count_list.append(b_count)
 L = [y-x for x,y in zip(b_count_list, b_count_list[1:])] #subtracting current value - previous, saves value into list
 for i in L:    
     new_throughput.append(i/self.t._interval)                                                                                                               
     self.f.write("%s,%s,%s,%s \n"%(self.experiment, b_count, b_count_list,new_throughput)) #write to file

运行此代码时,我会在CSV文件中获取此代码 picture here。 它每次都以某种方式打印出上一个值

我想要的是每一行的新行:

time , byte_count, throughput  
20181117013759,0.0,0.0  
20181117013759,14.3157348633,7.157867431640625  
0181117013759,53.5484619141,, 19.616363525390625  

Tags: 文件csvinselfnewfortimecount
1条回答
网友
1楼 · 发布于 2024-09-30 18:15:02

我没有一个有效的最小示例,但是您的最后一行应该引用每个列表的最后一个成员,而不是整个列表。大概是这样的:

 self.f.write("%s,%s,%s,%s \n"%(self.experiment, b_count, b_count_list[-1],new_throughput[-1])) #write to file

编辑:…尽管如果您希望这个简单的解决方案能够工作,那么您应该使用一个初始值初始化列表,例如[0],否则您将在第一次迭代时根据输出得到“列表索引超出范围错误”

相关问题 更多 >