简体   繁体   English

Python 将文本分成两行而不是打印一行

[英]Python splitting text into two lines instead of printing one

I'm reading sensor data with a RedBoard QWIIC.我正在使用 RedBoard QWIIC 读取传感器数据。 The program outputs data which looks like this:程序输出如下数据:

408 10  45.47   98760.30    23.33   413   19.17
    
400 7   45.45   98758.38    23.33   414   19.17
    
415 16  45.45   98757.56    23.33   414   19.17
    
405 3   45.45   98758.38    23.33   414   19.17

Yet when I run my Python program, the.txt file looks like this:然而,当我运行 Python 程序时,.txt 文件如下所示:

07/21/2022 14:12:49 400 0   45.42   98763.58    23.34   406
    19.17
    
07/21/2022 14:12:52 400 0   45.45   98759.20    23.34   406
    19.18
    
07/21/2022 14:12:55 400 0   45.48   98764.69    23.34   405
    19.18

The Python program in question:有问题的 Python 程序:

import serial
import time


serialPort_1 = 'COM3'
baud_rate = 9600
write_to_file_path = "test 1 7-21-22.txt"

output_file = open(write_to_file_path, "w+")
ser1 = serial.Serial(serialPort_1, baud_rate, timeout=4)

while 1:
    line1 = ser1.readline()

    line1 = line1.decode("utf-8")  
    print(time.strftime("%m/%d/%Y %H:%M:%S") + ' ' + line1)
    output_file.write(time.strftime("%m/%d/%Y %H:%M:%S")+' '+line1)


    time.sleep(0.00001)

How do I get the program to stop indenting between these last two values?如何让程序停止在这最后两个值之间缩进? I have already tried changing from printing a "\t" character after the sensor outputs to printing a few spaces instead.我已经尝试从在传感器输出后打印“\t”字符改为打印几个空格。

I found my solution.我找到了我的解决方案。 It all lies in the newline delimiter passed to the read_until() command.这一切都在于传递给 read_until() 命令的换行符分隔符。 For the input line, I use:对于输入行,我使用:

RedBoardline = RedBoardSerial.read_until()
RedBoardline = RedBoardline.rstrip()

This eliminated the 0x0A (aka ASCII code 10 or "\n") character at the end of the line.这消除了行尾的 0x0A(又名 ASCII 代码 10 或“\n”)字符。 Hope this helps someone.希望这可以帮助某人。

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

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