python serial read and write in in excel format

This is the place for queries that don't fit in any of the other categories.

python serial read and write in in excel format

Postby AJITnayak » Mon Mar 11, 2013 9:10 am

Dear all,
i am facing some problem in writing in to excel sheet.
Code: Select all
import serial
import csv
import os
import time


def main():
    pass

if __name__ == '__main__':
    main()
    COUNT=0
    while(COUNT<5):
      ser=serial.Serial()
      ser.port=12
      ser.baudrate=9600
      ser.open()
      str=ser.read(150)
      val=str.split(":")
      print "value is",val
      time_date=":".join(val[1:])
      print "date is ",time_date
      foo=open("time.txt","a+");
      print str
      foo.write(str)
      foo.write("\n")
      foo.close();
      ser.close()
      COUNT=COUNT+1



output:
value is ['calc dir', ' in FWD\r\nActuator On/OFF', '0\r\nMode', '1\r\nLocal Date & Time', '11/3/2013 14', '23', '21\r\nDesired Angle', '-15.32\r\n Actual Pos', '-10.40\r\n----------']
date is in FWD
Actuator On/OFF:0
Mode:1
Local Date & Time:11/3/2013 14:23:21
Desired Angle:-15.32
Actual Pos:-10.40


Here i want to indivually seprate datas like calc dir, mode,desire angle, actual pos. and run script such way that when it get executed data suppose to be written into paricular column without overlap. can some tell me modify code above
AJITnayak
 
Posts: 1
Joined: Mon Mar 11, 2013 8:17 am

Re: python serial read and write in in excel format

Postby setrofim » Mon Mar 11, 2013 10:27 am

Something like this (note: untested):
Code: Select all
import serial
import csv


if __name__ == '__main__':
    ser=serial.Serial()
    ser.port=12
    ser.baudrate=9600
    ser.open()

    with open("time.txt", "a+") as wfh:
        writer = csv.writer(wfh)
        for i in xrange(5):
            result = ser.read(150)
            writer.write(result.split(':'))

    ser.close()


You might wanna clean your values by removing the '\r\n' before you write them, etc; but that's the general idea. The key is to use a csv.writer and pass it a list containing the individual field values, rather than attempting to write the string you get from serial to file directly.
setrofim
 
Posts: 288
Joined: Mon Mar 04, 2013 7:52 pm


Return to General Coding Help

Who is online

Users browsing this forum: Baidu [Spider], snippsat and 4 guests