簡體   English   中英

Python 將文本分成兩行而不是打印一行

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

我正在使用 RedBoard QWIIC 讀取傳感器數據。 程序輸出如下數據:

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

然而,當我運行 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

有問題的 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)

如何讓程序停止在這最后兩個值之間縮進? 我已經嘗試從在傳感器輸出后打印“\t”字符改為打印幾個空格。

我找到了我的解決方案。 這一切都在於傳遞給 read_until() 命令的換行符分隔符。 對於輸入行,我使用:

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

這消除了行尾的 0x0A(又名 ASCII 代碼 10 或“\n”)字符。 希望這可以幫助某人。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM