Azeem Ahamed Azeem Ahamed - 21 days ago 5
Python Question

Writing Data to csv file to a single row

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

1,2,33,43343,4555,344323


In such a way all data to be in 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 each single row and multiple column.

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)

Answer

The csv module writes rows - every time you call writerow a newline is written and a new row is started. So, you can't call it multiple times and expect to get columns. You can, however, collect the data into a list and then write that list when you are done. The csv module is overkill for this.

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

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

data = []
for _ in range(5):
    data.append(ser.readline().strip())
    time.sleep(0.02)

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(data)

    # csv is overkill here unless the data itself contains commas
    # that need to be escaped. You could do this instead.
    # csvfile.write(','.join(data) + '\n')

UPDATE

One of the tricks to question writing here to to supply a short, runnable example of the problem. That way, everybody runs the same thing and you can talk about whats wrong in terms of the code and output everyone can play with.

Here is the program updated with mock data. I changed the open to "wb" so that the file is deleted if it already exists when the program runs. Run it and let me know how its results different from what you want.

import csv

filename = 'deleteme.csv'

test_row = '1,2,33,43343,4555,344323'
test_data = test_row.split(',')

data = []
for _ in range(5):
    data.append(test_data.pop(0).strip())
    time.sleep(0.02)

with open(filename, 'wb') as csvfile:
    spamwriter = csv.writer(csvfile,delimiter=',', lineterminator='\n')
    spamwriter.writerow(data)

assert open(filename).read().strip() == test_row, 'got one row'
Comments