当前位置: 动力学知识库 > 问答 > 编程问答 >

python - Writing varible strings and time to a file

问题描述:

I am writing my first program in python (first program ever for that matter). It's a simple program that detects input (On my raspberry pi) from a door chime and counts the number of times it goes off and prints the number of times on the screen followed by the date and time the event occurs.

So now I want to refine the program a bit; my first thought was to write the data to a file for later reviewing. I have figured out how to have my program create and open a file and even write simple strings to it, but getting it to write the strings with the variable (x) to it and the the variable 'time.strftime' to it has me stumped...

Here's my code:

 # 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)

网友答案:

Python print works in a different fashion.

Try this:

print("There have been"+ str(x) +"motion events!")

And this:

file.write('motion event recorded at: '+time.strftime("%m")+'\n')

Try posting what error you're receiving so that it's easier for people to answer.

Also, for a first time code, this is pretty good.

分享给朋友:
您可能感兴趣的文章:
随机阅读: