Feb-04-2022, 03:00 AM
Although the data can be written to file one row at a time in a loop the natural way to go for me would be to collect and save all the data then write it to a csv file in one chunk. That is the purpose of the csv modules csvwriter.writerows() and why it is often seen in the following format
with open('test.csv', "a+", newline ="") as csvfile: csvwriter = csv.writer(csvfile) csvwriter.writerows(fields) csvwriter.writerows(test_list)The writerows expects a list of lists as a parameter so the format of the header would be similar to this
fields = [['SLNo', 'Date','Time', 'RData', 'BData','GData','IRdata']]The list of lists that contain the data is not quite as straight forward but can be built as the data is collected, using your original count of 10 to simulate data collection this is my take on collecting 10 rows of data and packing them in a list of lists then writing the header and data to file in one go
from datetime import datetime import csv fields = [['SLNo', 'Date','Time', 'RData', 'BData','GData','IRdata']] test_list=[] data_string="" count=0 while(count<10): print("Counter:",count) now = datetime.now() Sln0=count date_Format=now.strftime('%Y/%m/%d ') current_time = now.strftime("%I:%M:%S") data_string=(str(Sln0) + "," + date_Format + "," + current_time) test_list.append([]) #creates a list of lists test_list[count]=data_string.split(",") count=count+1 with open('test.csv', "a+",newline="") as csvfile: csvwriter = csv.writer(csvfile) csvwriter.writerows(fields) csvwriter.writerows(test_list)[color=#?][/color]