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>When working with small files that are exclusive to you, simply cache their content. This is faster and healthier for your storage.</p>

<pre><code># start of the script
# load the current value
import ast
status, status_file = False, "state.txt"
with open(status_file) as stat_file:
    status = ast.literal_eval(next(stat_file()))

# keep on looping, check against *known value*
while True:
    current_status = get_door_status()
    if current_status != status:  # only update on changes
        status = current_status  # update internal variable
        # open for writing overwrites previous value
        with open(status_file, 'w') as stat_file:
            stat_file.write(status)
</code></pre>

python linux