How to check if the first line has changed in a text file using python

Question:

I’m trying to write a script that will check if the first line of a text file has changed and print the value once. It needs to be an infinite loop so It will always keep checking for a change. The problem I’m having is when the value is changed it will keep constantly printing and it does not detect the new change.
What I need to is the script to constantly check the first line and print the value once if it changes and do nothing if it does not change.
This is what I tried so far:

def getvar():
    with open('readme.txt') as f:
        first_line = f.readline().strip('n')
    result = first_line
    return result

def checkvar():
    initial = getvar()
    print("Initial var: {}".format(initial))
    while True:
        current = getvar()
        if initial == current:
            pass                                
        else:
            print("var has changed!")
            pass

checkvar() 
Asked By: Ken Robertson

||

Answers:

If the initial line has changed, set initial to current.
In the function checkvar()

def checkvar():
     initial = getvar()
     print("Initial var: {}".format(initial))
     while True:
        current = getvar()
        if initial == current:
            pass                                
        else:
            initial = current #initial line set to current line
            print("var has changed!")
            pass
Answered By: Devansh_Jain_21

You are never re-assigning initial, so when you check if initial == current, it’s only checking against the very first version of the file. Instead, re-assign as follows

def getvar():
    with open('readme.txt') as f:
        first_line = f.readline().strip('n')
    result = first_line
    return result

def checkvar():
    last = getvar()
    while True:
        current = getvar()
        if last != current:
            print("var has changed!")
            last = current

checkvar()
Answered By: Justin Chang
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.