[英]Python, write text in TXT file
I'm starting off with my RPI alarm clock, now I managed to make a button execute a shell-script that terminates my alarm. 我从RPI闹钟开始,现在我设法使按钮执行终止我的闹钟的shell脚本。 I'm looking of buying a toggling-switch now the script I'd really like is.
我现在打算购买一个切换开关,我真正想要的脚本是。
if pin = 1
then = "write to status.txt : awake
if pin = 0
then = "write to status.txt : sleeping
I can add the rules to start/stop my alarm scripts myself but on this one I really need some help. 我可以自己添加规则来启动/停止我的警报脚本,但是在这方面我确实需要一些帮助。
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")
or 要么
append_to_file("status.txt", ("awake\n" if pin else "sleeping\n"))
with open('status.txt', 'w') as status:
if pin == 1:
status.write('awake')
elif pin == 0:
status.write('sleeping')
Although if pin
could ever potentially be anything else you may want to avoid opening the file unnecessarily. 尽管如果
pin
可能还有其他用途,您可能要避免不必要地打开文件。
if pin in [0, 1]:
with open( …
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.