I've been trying to send the data I am receiving from a serial port. I'm reading the ASCII data from my device by using the serial.readline()
. When I use this function in the main loop, I can print the string but I cannot send it to my output file. My f.write()
function is not working when I place the readline()
in the loop. Any idea how to solve this problem?
import serial
import csv
ser=serial.Serial('COM6', 9600, 8, parity='N', timeout=2)
with open('output.csv','a') as f:
while True:
line = ser.readline()
if line:
print(line)
f.write(line)
This is the data I get, but nothing in the output file.
0R5,Th=24.3C,Vs=24.2V
0R2,Ta=23.3C,Ua=21.3P,Pa=1026.9H
0R1,Dm=000#,Sm=99.9#
0R5,Th=24.3C,Vs=24.2V
File will be flushed when buffer if full and closed when you exit with
block.
If you stay in loop forever no changes in file will not be seen until buffer is filled.
You can change buffering on output file. See How often does python flush to a file?
In your example you could use
with open('output.csv', 'a', buffering=0) as f: