python变量作为字符串

时间:2017-07-12 05:43:17

标签: python python-3.x

当我运行以下内容时,我得到了打印所需的输出。然后我尝试将结果插入到我的创建文件中。我可以在那里输入一个property.text值,它可以正常工作或只是'字符串'但是当我试着在那里调用结果时,它只是做了什么。

alarms = system.alarm.queryStatus(state=["ActiveUnacked", "ClearAcked"])

for alarm in alarms: 
print alarm.getName(), alarm.getState()

结果

Dryer 7 Temp low Cleared, Acknowledged
Dryer 10 Temp High Cleared, Acknowledged
Dryer 5 Burner Fault Cleared, Acknowledged

当我运行这个

alarms = system.alarm.queryStatus(state=["ActiveUnacked", "ClearAcked"])
for alarm in alarms: 
alarm1 = alarm.getName(), alarm.getState()

my_file = open('D:\send_file3.txt','w')
my_file.write('from call import Client\n')
my_file.write('account_sid = "test"\n')
my_file.write('auth_token = "test"\n')
my_file.write('client = Client(account_sid, auth_token)\n')
my_file.write('message =client.api.account.messages.create(to="+6140000000", 
from_="+614000000000", body=" ')
my_file.write(alarm1)
my_file.write(' ")') 
my_file.close()

文本文件输出

它将所有行写入

body="

然后空白。如果我将alarm1更改为' hello'

我得到body="hello ")。

我想要实现的是

body="Dryer 7 Temp low Cleared, Acknowledged Dryer 10 Temp High Cleared, Acknowledged Dryer 5 Burner Fault Cleared, Acknowledged"

任何帮助将不胜感激

2 个答案:

答案 0 :(得分:0)

对此任务使用字符串格式。 More info

 alarms = system.alarm.queryStatus(state=["ActiveUnacked", "ClearAcked"])
    for alarm in alarms: 
        alarm1 = alarm.getName(), alarm.getState()
        my_file = open('D:\send_file3.txt','w')
        my_file.write('from call import Client\n')
        my_file.write('account_sid = "test"\n')
        my_file.write('auth_token = "test"\n')
        my_file.write('client = Client(account_sid, auth_token)\n')
        my_file.write('message=client.api.account.messages.create(to="+6140000000", from_="+614000000000", body=\"{}\"').format(alarm1)
        my_file.close()

答案 1 :(得分:0)

由于alarm不是字符串/文本,因此无法将其直接写入文件。您可以通过将alarm.getName()alarm.getState()放在列表中并使用分隔符","将它们作为字符串连接来实现此目的。然后你可以把它写到文件

my_file = open('D:\send_file3.txt','w')
my_file.write('from call import Client\n')
my_file.write('account_sid = "test"\n')
my_file.write('auth_token = "test"\n')
my_file.write('client = Client(account_sid, auth_token)\n')
my_file.write('message =client.api.account.messages.create(to="+6140000000", 
from_="+614000000000", body=" ')
for alarm in alarms: 
    myfile.write(",".join([alarm.getName(), alarm.getState()]))