簡體   English   中英

我需要將txt文件作為特定功能的列表導入

[英]I need to import a txt file as a list for a specific function

我正在嘗試保存並加載傳感器的校准數據。 我能夠讀取校准數據並將其保存到文本文件中。 查看文本文件時,在一組方括號中有22個數字,每個逗號之間用逗號隔開。

我需要以set_calibration函數將其讀取的方式導入該文本文件。

這是設置的校准功能。

def set_calibration(self, data):
    """Set the sensor's calibration data using a list of 22 bytes that
    represent the sensor offsets and calibration data.  This data should be
    a value that was previously retrieved with get_calibration (and then
    perhaps persisted to disk or other location until needed again).
    """
    # Check that 22 bytes were passed in with calibration data.
    if data is None or len(data) != 22:
        raise ValueError('Expected a list of 22 bytes for calibration data.')
    # Switch to configuration mode, as mentioned in section 3.10.4 of datasheet.
    self._config_mode()
    # Set the 22 bytes of calibration data.
    self._write_bytes(ACCEL_OFFSET_X_LSB_ADDR, data)
    # Go back to normal operation mode.
    self._operation_mode()

問題是,這是我第一次使用python,我的編碼經驗很少。 我嘗試了這個:

calfile=open("calibrate.txt","r")
caldata=calfile.readlines()
calfile.close()

之后,caldata將打印為“ ['[242、255、0、0、27、0、65、2、139、3、174、255、255、255、255、255、0、0、232、3, 102,3]']“,但是set_calibration函數返回“期望的22個字節的列表用於校准數據”。 錯誤。 當以

bno.set_calibration(caldata)

我不確定這有多大幫助,但是傳感器是Adafruit BNO055,我正在使用Raspberry Pi運行它。 我有一種強烈的感覺,我正在濫用和/或濫用讀取功能,但是,就像我說的那樣,我對此很陌生。

calfile.readlines()不需要在這里使用。 如果您的數字都在文件的不同行上,並且沒有逗號或方括號,那將是這樣的:

23
51
32

因為您的電話號碼已經是列表樣式的格式(即用逗號和方括號括起來),所以我們需要將其轉換為真實列表,而不是字符串形式的數字。 為此,將您的代碼在calfile=open...calfile.close()之間calfile=open...

caldata=[int(x.strip()) for x in calfile.read()[1:-1].split(",")]

這是一個列表理解,它將文件的內容轉換為實際的Python列表。

之所以會出現此問題,是因為caldata中的值是一個字符串,因此長度不是22。

暫無
暫無

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

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