'Writing Data to csv file to a single row

I need to write data to a single row and column by where data is coming from the serial port. So I used to read and write row by row. But the requirement is I need to write data to the next column of a single row In PYTHON. I need to have filed at the end like this

1,2,33,43343,4555,344323

In such a way all data is to be in a single row and multiple columns, and not in one column and multiple rows.

So this writes data in one after one row.

1

12

2222

3234

1233

131

but I want 1 , 12 , 2222 , 3234 , 1233 , 131 like every single row and multiple columns.

import serial
import time
import csv
ser = serial.Serial('COM29', 57600)

timeout = time.time() + 60/6   # 5 minutes from now

while True:
    test = 0
    if test == 5 or time.time() > timeout:
        break
    ss=ser.readline()
    print ss
    s=ss.replace("\n","")
    with open('C:\Users\Ivory Power\Desktop\EEG_Data\Othr_eeg\egg31.csv', 'ab') as csvfile:
        spamwriter = csv.writer(csvfile,delimiter=',', lineterminator='\n')
        spamwriter.writerow([ s ])
        csvfile.close()
    time.sleep(0.02)

  


Solution 1:[1]

Assuming your serial port data wouldn't overrun your main memory heap, the following would be the code that would suit your need.

import serial
import time
import csv
ser = serial.Serial('COM29', 57600)

timeout = time.time() + 60/6   # 5 minutes from now

result = []
while True:
    test = 0
    if test == 5 or time.time() > timeout:
        break
    ss=ser.readline()
    print(ss)
    s=ss.replace("\n","")
    result.append(s)
    time.sleep(0.02)

with open('C:\Users\Ivory Power\Desktop\EEG_Data\Othr_eeg\egg31.csv', 'w') as csvfile:
    spamwriter = csv.writer(csvfile,delimiter=',', lineterminator='\n')
    spamwriter.writerow([result])
    csvfile.close()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1