简体   繁体   English

Python csv 数据记录在 while 循环中不起作用

[英]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.我一直在尝试通过 USB 端口记录从 Arduino 接收到的数据,奇怪的是代码在我的 mac 上运行得很好,但在 windows 上它不会写它。 At the start I expected the initial writing "DATA" but it didn't even write that.一开始我期望最初的写作“DATA”,但它甚至没有写。 And when I commented out the entire loop it worked (It says "DATA" in the csv file).当我注释掉整个循环时,它起作用了(它在 csv 文件中显示“数据”)。

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.我认为它在 Windows 中不起作用,因为您需要寻找 CR LF。

Might try using Environment.NewLine as it will act as any of the above depending on the operating system.可以尝试使用Environment.NewLine因为它会根据操作系统充当上述任何一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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