【问题标题】:Python, write text in TXT filePython,在TXT文件中写入文本
【发布时间】:2014-02-09 15:31:30
【问题描述】:

我从我的 RPI 闹钟开始,现在我设法让一个按钮执行一个 shell 脚本来终止我的闹钟。我想买一个拨动开关 现在我真正想要的脚本是。

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

我可以自己添加规则来启动/停止我的警报脚本,但在这方面我真的需要一些帮助。

【问题讨论】:

    标签: python button raspberry-pi alarm


    【解决方案1】:
    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"))
    

    【讨论】:

      【解决方案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( …
      

      【讨论】:

        猜你喜欢
        • 2021-10-17
        • 2016-08-17
        • 1970-01-01
        • 2021-07-15
        • 1970-01-01
        • 1970-01-01
        • 2011-05-06
        • 2013-12-24
        • 2016-01-08
        相关资源
        最近更新 更多