Python 将可变字符串和时间写入文件

Python 将可变字符串和时间写入文件,python,Python,我正在用python编写我的第一个程序(有史以来第一个这样的程序)。这是一个简单的程序,可以检测来自门铃的输入(在我的raspberry pi上),计算它发出的次数,并在屏幕上打印次数,然后是事件发生的日期和时间 所以现在我想对程序进行一点改进;我的第一个想法是将数据写入一个文件,以便以后进行审查。我已经知道了如何让我的程序创建和打开一个文件,甚至向其中写入简单的字符串,但是让它向其中写入变量(x)和变量“time.strftime”的字符串让我很困惑 这是我的密码: # My first p

我正在用python编写我的第一个程序(有史以来第一个这样的程序)。这是一个简单的程序,可以检测来自门铃的输入(在我的raspberry pi上),计算它发出的次数,并在屏幕上打印次数,然后是事件发生的日期和时间

所以现在我想对程序进行一点改进;我的第一个想法是将数据写入一个文件,以便以后进行审查。我已经知道了如何让我的程序创建和打开一个文件,甚至向其中写入简单的字符串,但是让它向其中写入变量(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)

Python打印以不同的方式工作

试试这个:

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

file.write('motion event recorded at: '+time.strftime("%m")+'\n')
尝试发布您收到的错误,以便人们更容易回答


而且,对于第一次编写代码来说,这相当不错。

我很高兴事情都解决了。如果此答案确实有用,请将此标记为已接受的答案。谢谢,非常感谢您的帮助。我还根据您的示例了解了如何将计数器添加到文件中。以下是我所做的:file.write(str(x))file.write('motion event recorded at:'+time.strftime(“%m/%d/%y%H:%m:%s”)+'\n')为什么我的代码没有正确显示我上面的注释?所以实际上你可以简单地编写这个
文件。write(str(x)+-“+”运动事件记录在:“+time.strftime(“%m/%d/%y%H:%m”)+'\n')
。另外,要显示代码,请在代码块周围使用波浪号(~)上方的符号。酷!再次感谢,是的,我试图让这一切都发生在一行,但我没能弄明白。一旦我让它像我那样工作,我就把它敲出来了!不过,我会改成你刚才给我看的方式,因为这可能是一种“更干净”的方式。再次感谢!