0

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)        
2
  • 1
    If your intention is to append the data to the file every 5th iteration, then open the file in append mode, rather than write mode. Otherwise, you'll just overwrite you old data every time. Commented Nov 13, 2018 at 10:28
  • No, I want to write 5 different file Commented Nov 13, 2018 at 10:35

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

I need five different files and not in a single file.
In this case, using the code from above, you could iterate through the 5 entries of past_data and append each entry to a different file. An alternative is to create a list of five files cache = [[fileA], ..., [fileE]] and write tocache[i%5] after iteration i.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.