1
我正在用python編寫我的第一個程序(有史以來的第一個程序)。這是一個簡單的程序,可以檢測來自門鈴的輸入(在我的樹莓派上),並統計它發生的次數,並在屏幕上打印次數,然後顯示事件發生的日期和時間。將可變字符串和時間寫入文件
所以現在我想細化一下程序;我的第一個想法是將數據寫入文件供以後查看。我已經想出瞭如何讓我的程序創建並打開一個文件,甚至寫一些簡單的字符串,但是讓它用變量(x)寫入字符串以及它的變量'time.strftime'難倒...
這裏是我的代碼:以不同的方式
# 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)
嗯,我很高興事情解決。如果這個答案確實有幫助,請將此標記爲已接受的答案。 – ishaan
謝謝,你的幫助是非常感謝。我還想出瞭如何根據您的示例將計數器添加到文件中。這是我做的: file.write(str(x)) file.write('motion event at:'+ time.strftime(「%m /%d /%y%H:%M:%S 「)+'\ n') –
爲什麼我的代碼不是我上面的評論顯示正確? –