Python 我需要导入一个txt文件作为特定函数的列表

Python 我需要导入一个txt文件作为特定函数的列表,python,raspberry-pi,Python,Raspberry Pi,我正在尝试保存并加载传感器的校准数据。我能够读取校准数据并将其保存到文本文件中。当查看文本文件时,有22个数字由comas分隔,都在一组方括号中 我需要以set_校准函数读取的方式导入该文本文件 以下是设置校准功能 def set_calibration(self, data): """Set the sensor's calibration data using a list of 22 bytes that represent the sensor offsets and c

我正在尝试保存并加载传感器的校准数据。我能够读取校准数据并将其保存到文本文件中。当查看文本文件时,有22个数字由comas分隔,都在一组方括号中

我需要以set_校准函数读取的方式导入该文本文件

以下是设置校准功能

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、255、0、0、232、3、102、3]””,但set_calibration函数返回“校准数据的预期22字节列表”。错误。当运行为

bno.set_calibration(caldata)
我不确定这会有多大帮助,但传感器是Adafruit BNO055,我正在使用树莓Pi运行它。我有一种强烈的感觉,我正在滥用和/或滥用read函数,但是,正如我所说,我对这一点非常陌生。

calfile.readlines()
不是您需要在这里使用的。如果您的数字都在文件的不同行上,没有逗号或方括号,则为:

23
51
32
因为您的数字已经是列表样式的格式(即带有逗号和方括号),所以我们需要将其转换为实际列表,而不是一个列表的字符串表示形式。为此,将
calfile=open…
calfile.close()
之间的代码替换为:

caldata=[int(x.strip()) for x in calfile.read()[1:-1].split(",")]
这是一个列表理解,可以将文件的内容转换为实际的Python列表。

calfile.readlines()
不是这里需要使用的。如果您的数字都在文件的不同行上,没有逗号或方括号,则为:

23
51
32
因为您的数字已经是列表样式的格式(即带有逗号和方括号),所以我们需要将其转换为实际列表,而不是一个列表的字符串表示形式。为此,将
calfile=open…
calfile.close()
之间的代码替换为:

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

这是一个列表理解,将文件内容转换为实际的Python列表。

您遇到这个问题是因为caldata中的值是字符串,所以长度不是22。

您遇到这个问题是因为caldata中的值是字符串,所以长度不是22