Write from Serial to file

Viewed 38

Im trying to write a script that will constantly listen to a serial device and write everything to a file. But its not writing anything to the file. What am I doing wrong?

import serial
import time

i = 0

ser = serial.Serial('/dev/cu.SLAB_USBtoUART', 115200, timeout = 1)

while True:
    readOut = ser.readline().decode('ascii')
    file = open("output.txt","w")
    file.write(readOut)
    file.close()
1 Answers

You're opening it as w each time, which erases the content. Change to:

import serial
import time

i = 0

ser = serial.Serial('/dev/cu.SLAB_USBtoUART', 115200, timeout = 1)

while True:
    readOut = ser.readline().decode('ascii')
    file = open("output.txt","a")
    file.write(readOut)
    file.close()
Related