I need help in python2 to making a counter that can count up and store the count data into a file
Question: This is my code, I have to add a counter into my code so that every time the
button is pressed it will count up once and i would like to to keep on
counting up every time the button is pressed. I searched online and found out
that I have to store the counter data to a file but i do not know how to write
a code to do the count and store the count to a file. please help

    
    
    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)
    


Answer: Such a program will help you:

    
    
    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)
    

As you see below, it shares a counter between different runs:

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

