我需要python2中的帮助来制作一个可以计数并将计数数据存储到文件中的计数器

时间:2016-04-20 11:46:53

标签: python python-2.7 count counter

这是我的代码,我必须在我的代码中添加一个计数器,这样每次按下按钮它都会计数一次,我想在每次按下按钮时继续计数。我在网上搜索并发现我必须将计数器数据存储到文件中,但我不知道如何编写代码来进行计数并将计数存储到文件中。请帮忙

from time import sleep
import RPi.GPIO as GPIO
import os
import sys
import webbrowser

GPIO.setmode(GPIO.BOARD)

button=40
button1=11

car=("/home/pi/Desktop/htb.mp4")
car2=("/home/pi/Desktop/htb2.mp4")

GPIO.setup(button,GPIO.IN)
GPIO.setup(button1,GPIO.IN)
quit_video=True
player=False

while(1):
    if GPIO.input(button)==0 and GPIO.input(button1)==1:
        print " thru beam  "
        os.system('pkill omxplayer')
        os.system('omxplayer -r htb.mp4')
        sleep(.5)
    if GPIO.input(button1)==0 and GPIO.input(button)==1:
        print " that other sensor "
        os.system('pkill omxplayer')
        os.system('omxplayer -r htb2.mp4')
        sleep(.5)
    else:
        print " home "
        webbrowser.open('https://www.google.com.sg/')
        sleep(.5)

1 个答案:

答案 0 :(得分:0)

这样的程序会帮助你:

import os

if not os.path.isfile("counter.txt"):
    counter = 1
    f = open("counter.txt","w+")
    f.write(str(counter))
    f.close()
    print (counter)
else:
    f = open("counter.txt","r+")
    counter = int(f.readline())
    counter += 1
    f.seek(0)
    f.write(str(counter))
    f.close()
    print (counter)

如下所示,它在不同的运行之间共享一个计数器:

Python 2.7.10 (default, May 23 2015, 09:44:00) [MSC v.1500 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>> 
1
>>> ================================ RESTART ================================
>>> 
2
>>> ================================ RESTART ================================
>>> 
3
>>> ================================ RESTART ================================
>>> 
4
>>> ================================ RESTART ================================
>>> 
5
>>>