Python,在TXT文件中写入文本

时间:2014-02-09 15:31:31

标签: python button raspberry-pi alarm

我开始使用我的RPI闹钟,现在我设法让一个按钮执行一个shell脚本来终止我的闹钟。我正在寻找买一个切换开关 现在我真正喜欢的剧本是。

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

我可以自己添加启动/停止闹钟脚本的规则,但是在这一点上我真的需要一些帮助。

2 个答案:

答案 0 :(得分: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"))

答案 1 :(得分: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( …
相关问题