I am reading a string from the serial port using pySerial and then writing data to a file with a time stamp. For some reason a new line is written with an empty data entry ( with the time stamp) every time I connect the serial port. I have set the write to file as append so that every time I read data from the port I can use the same file. Is there anything fundamental that I am missing in setting up the serial port? I have attached the code and the output written in the file. Thanks a lot!
sPrt = serial.Serial( port = 5, baudrate = 9600 , bytesize = 8 )
sPrt.flushInput()
while True:
data = sPrt.readline().decode('utf-8')[:-2]
print(data)
dateTimeObj = datetime.now()
timeStamp = dateTimeObj.strftime("%d-%b-%Y %H:%M")
with open(fileName,"ab") as f:
writer = csv.writer(f,delimiter=",")
writer.writerow([timeStamp,data])
and the output in the file is: Here I started data logging at 14:43, disconnected the port after two data points and then connected it again at 14.44. Each time a new connection was made a line without any data got added to the saved file
16-Nov-2022 14:43,
16-Nov-2022 14:43,"A"
16-Nov-2022 14:43,"B"
16-Nov-2022 14:44,
16-Nov-2022 14:44,"A"
The output of the print(data) line is:
A
B
A
I tried to check if the data variable is a "\n" and to only write to file if it isnt but that did not seem to do anything .
I don't see the problem here, apparently
data
is either something like'A'
(no newline) or''
(no newline, just an empty string). In either case,.writerow()
will write a full row, followed by a newline.If you don't want newlines written to the output file:
I don't see it working with
"ab"
anyway, since thecsv.writer
expects to be writing to a text file, not a binary one. As do you apparently, since you called.decode()