Update a text file with python only if it has changed
<p>Ok, I have my raspberry pi hooked up to a magnetic sensor on my garage door. I have a python script that update a website (initailstate.com) every second and reports changes, but it costs money after 25k requests and I killed that very quickly lol. 
I want to instead to update a text file every time the state of the door changes.(open/closed) I have a text file called data.txt. I have a web page that uses java script to read the txt file and uses ajax to update and check the file for changes. this all works as i want but how can i get python to update a text file if and only if the contents of the file are different?  </p>

<p>I am looking to use python to update the text file once the door changes states. I could use a database but I figured a text file would be easier to start with.
Let me know what you need from me if i haven't been specific enough.</p>

<p>Maybe you could try something like this:</p>

<pre><code>f = open("state.txt", "w+") # state.txt contains "True" or "False"

def get_door_status():
    # get_door_status() returns door_status, a bool
    return door_status

while True:
    door_status = str(get_door_status())
    file_status = f.read()
    if file_status != door_status:
        f.write(door_status)
</code></pre>

python linux