2014-09-26 64 views
-3

我是新的Python世界,但喜歡學習,所以我寫了一個小代碼,但它給了我這個錯誤。疼痛的'str'和'列表'對象

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

而不是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)))

+0

感謝它的完美。所以我可以去閱讀部分.. – 2014-10-01 20:18:48