使用Python将串行数据存储到文本文件中

2024-09-30 01:31:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用下面的Python代码来存储我从加速度计MMA7361L接收到的数据。该文件是创建的,但没有任何数据被写入?

我需要将数据存储到文件中,以防止数据丢失。数据由Arduino发送,作为我的微控制器,连接我的加速计。

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

Tags: 文件数据代码inimportforcloseport
3条回答

你可以这样做,我现在就这样做,而且很有效。我还有另外一个,它告诉您正在使用什么com端口,如果存在com端口来运行while loop,如果不存在,则关闭文件。

import serial
import csv

file = raw_input('Save File As: ')
saveFile = open(file, 'w')

serialport = raw_input('Enter Port: ')
port1 = serialport

print "Connecting to....", port1

arduino = serial.Serial(port1, 9600)

print "Arduino detected"

while True: 
    time.sleep(.01)
    data = arduino.readline()
    saveFile.write(data)
    print data
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()

将文件模式更改为“ab”,它应该可以工作。a+b仅当您在向其追加数据时还想读取内容时才有用。

除非在这里需要进行认真的优化,否则在开始时读取整个文件,然后用“ab”模式将数据追加到文件中重新打开文件会更容易。

相关问题 更多 >

    热门问题