我正在编写我的第一个程序在python(有关此事的第一个程序)。它是一个简单的程序,可以从门铃中检测输入(在我的覆盆子pi上)并计算它关闭的次数并在屏幕上打印次数,然后是事件发生的日期和时间。
所以现在我想稍微改进一下这个程序;我的第一个想法是将数据写入文件以供以后查看。我已经想出如何让我的程序创建并打开一个文件,甚至为它编写简单的字符串,但让它用变量(x)写入字符串和变量' time.strftime&#39 ;它让我难过......
这是我的代码:
# My first program
# version 1.1
# Goal is to write each motion event to a file
import time
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(24,GPIO.IN)
# input = GPIO.input(24)
#temp code so I don't have to keep walking to the sensor called in the line commented out above.
a = int(raw_input("Enter a number"))
x = 0
while True:
#if (GPIO.input(24)):
#again temp code, just the 'if a>0:'
if a>0:
x += 1
print "There have been %d motion events!" % (x)
print "The last one was on: "
print time.strftime("%m/%d/%y %H:%M:%S")
print
# Open the file that will hold the history data
#this is where I am stuck...
with open('history.dat', 'a') as file:
file.write('motion event recorded at: %s \n') %time.strftime("%m")
file.close()
#pause the program to prevent multiple counts on a single person triggering the chime - some folks are slow ;)
time.sleep(4)
答案 0 :(得分:1)
Python打印以不同的方式工作。
试试这个:
print("There have been"+ str(x) +"motion events!")
而且:
file.write('motion event recorded at: '+time.strftime("%m")+'\n')
尝试发布您收到的错误,以便人们更容易回答。
此外,对于第一次使用的代码,这非常好。