在python中几次迭代后将数据写入文件

时间:2018-11-13 10:25:55

标签: python

我想在第五次迭代中将数据写入五个文件,有什么方法可以做,我很困惑如何获取过去的数据

   i=1
   while 1:
   data = random.randint(0,100) 
   print(data)
   if(i%5==0):
       with open('D:\mydata\my%d.csv'%(i-4),'D:\mydata\my%d.csv'%(i-3), "w") as csv_file:   
           writer = csv.writer(csv_file, delimiter=',')
           level_counter = 0
           max_levels = 1
           while level_counter < max_levels:
               filename1 = data
               writer.writerow(("No load", filename1)) 
               level_counter = level_counter +1 
               print("done")
   i=i+1
   time.sleep(2)        

1 个答案:

答案 0 :(得分:1)

只需使用列表来存储过去5次迭代中的数据:

i = 1
past_data = []
while True:
    data = random.randint(0, 100)
    past_data.append(data)
    if i % 5 == 0:
        ...
        past_data = []
i += 1