Storing serial data onto a text file using Python


Question

I'm using the following Python code to store the data I receive from the accelerometer MMA7361L. The file is created but without any data being written?

I need to store the data onto the file to prevent loss of data. The data is sent by an Arduino, as my microcontroller, that connects my accelerometer.

import serial

port = serial.Serial('COM4', 9600)

for i in range(0, 10):
    abc=open('abc.txt', 'r+b')  //append and binary(a+b) mode
    x = port.read(size=1)//   1 byte
    print x
    abc.write(x)
    abc.close()

port.close()
1
2
1/20/2011 7:57:36 PM

import serial

addr  = 'COM4'
baud  = 9600
fname = 'accel.dat'
fmode = 'ab'
reps  = 10

with serial.Serial(addr,baud) as port, open(fname,fmode) as outf:
    for i in range(reps):
        x = port.read(size=1)
        print x
        outf.write(x)
        outf.flush()
3
1/8/2011 7:04:23 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon