kn_pro
kn_pro

Reputation: 67

Writing data to files after few iteration in python

I want to write data into five files on every fifth iteration, is there any way to do that, I am confused how to fetch the past data

   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)        

Upvotes: 0

Views: 188

Answers (1)

randomwalker
randomwalker

Reputation: 1703

Just use a list to store data from the past 5 iterations:

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

Upvotes: 1

Related Questions