0

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
HuHu
  • 25
  • 6
  • Please, fix the indentation - I guess the whole `while loop` needs to be indented by one level. i,e, if your code do look like this you will get IndentationError – buran Dec 13 '18 at 08:13
  • Yes, my error when placed the code here. Thanks. – HuHu Dec 13 '18 at 09:29

1 Answers1

0

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:
Frane
  • 534
  • 6
  • 13
  • 1
    Great! It solved my problem. I am able to send the data to my output file. Thanks! – HuHu Dec 13 '18 at 09:31