2014-02-09 175 views
1

我从我的RPI闹钟开始,现在我设法让一个按钮执行一个shell脚本来终止我的闹钟。我期待购买切换开关 现在我真的很喜欢的脚本是。Python,在TXT文件中写入文本

if pin = 1 
    then = "write to status.txt : awake 
if pin = 0 
    then = "write to status.txt : sleeping 

我可以添加规则来开始/停止我的报警脚本,但在这一个我真的需要一些帮助。

回答

2
with open('status.txt', 'w') as status: 
    if pin == 1: 
    status.write('awake') 
    elif pin == 0: 
    status.write('sleeping') 

虽然如果pin可能永远可能是其他任何你可能希望避免打开文件不必要的。

if pin in [0, 1]: 
    with open(… 
3
def append_to_file(fname, s): 
    with open(fname, "a") as outf: 
     outf.write(s) 

if pin: 
    append_to_file("status.txt", "awake\n") 
else: 
    append_to_file("status.txt", "sleeping\n") 

append_to_file("status.txt", ("awake\n" if pin else "sleeping\n"))