我是python世界的新手但是喜欢学习,所以我写了一些代码,但它给了我这个错误。
TypeError: cannot concatenate 'str' and 'list' objects
请向我解释该怎么做。
#!/usr/bin/python
# -*- coding: utf-8 -*-
# import the server implementation
import subprocess
import time
from time import strftime
from pymodbus.client.sync import ModbusSerialClient as ModbusClient
# Time and date variable
t_date = format(strftime('%Y%m%d'))
t_time = format(strftime('%H%M'))
# READ VALUES
# choose the serial client
client = ModbusClient(method='rtu', port='/dev/ttyUSB0', baudrate=9600, stopbits=1, parity='N', bytesize=8, timeout=1)
client.connect()
ra = client.read_input_registers(0,44)
rb = client.read_input_registers(45,18)
with open("data.tmp", 'w', 1) as f:
data = ra.registers + rb.registers
f.write(str(data))
DATA.TMP中的结果如下:
[1, 0, 710, 3287, 2, 0, 710, 0, 0, 0, 0, 0, 639, 4997, 2257, 3, 0, 639]
我想为它添加日期和时间并迷失赞誉[]
所以我会得到这个:
20140926,1635,1, 0, 710, 3287, 2, 0, 710, 0, 0, 0, 0, 0, 639, 4997, 2257, 3, 0, 639
这可以简单地完成吗?
答案 0 :(得分:0)
而不是str(data)
使用', '.join(map(str,data))
。这会将列表转换为字符串:
>>> data = [1, 0, 710, 3287, 2, 0, 710, 0, 0, 0, 0, 0, 639, 4997, 2257, 3, 0, 639]
>>> ', '.join(map(str,data))
'1, 0, 710, 3287, 2, 0, 710, 0, 0, 0, 0, 0, 639, 4997, 2257, 3, 0, 639'
然后,您可以根据需要将其写入f
:
f.write('foo, bar, ' + ', '.join(map(str,data)))
(或将foo和bar添加到数据,只添加f.write(', '.join(map(str,data)))
)