简体   繁体   中英

Python csv data logging doesn't work in while loop

I have been trying to log the data received from the Arduino through USB port and the strange thing is that the code works on my mac just fine but on windows it won't write it. At the start I expected the initial writing "DATA" but it didn't even write that. And when I commented out the entire loop it worked (It says "DATA" in the csv file).

import serial

count = 1
port = serial.Serial('COM4', baudrate=9600, bytesize=8)
log = open("data_log.csv", "w")
log.write("DATA")
log.write("\n")
while 1:
    value = str(port.read(8), 'utf-8')
    value = value.replace('\r', '').replace('\n', '')
    if value.strip():
        log.write(str(count))
        log.write(',')
        log.write(value)
        log.write('\n')
        print(count)
        count += 1
    print(value)
\n = CR (Carriage Return) // Used as a new line character in Unix
\r = LF (Line Feed) // Used as a new line character in Mac OS
\n\r = CR + LF // Used as a new line character in Windows

I think it's not working in windows because you need to look for a CR LF.

Might try using Environment.NewLine as it will act as any of the above depending on the operating system.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM