Search code examples
pythonasynchronouslast-modified

Why is os.path.getmtime() always running twice? It does not make any sense


Here is the code:

import os
import asyncio
async def func_placing_sell_orders():
    prev_final_stocks_list_state = os.path.getmtime('stock_data//final_stocks_list.json')
    print('i run once')
    while True:
        if (prev_final_stocks_list_state != os.path.getmtime('stock_data//final_stocks_list.json')):
            prev_final_stocks_list_state = os.path.getmtime('stock_data//final_stocks_list.json')
            print('here')

asyncio.get_event_loop().run_until_complete(func_placing_sell_orders())

simplified ver:

import os
def simple():
    state = os.path.getmtime('file.json')
    print('i run once')
    while True:
        if (state != os.path.getmtime('file.json')):
            state = os.path.getmtime('file.json')
            print('here')

simple()

This is the print out:

i run once
here
here

here, gets print out twice every time I save the file. I ran to check the time between previous and current modified time and it is always different, which implies it should only run once per save.

This is so basic I don't understand why I'm getting this result. Please send help


Solution

  • If the file is large enough maybe the first "here" is while file is still writing edits and the last "here" is after the saving is done. Also, if you're using something like open("file", "w") or something like this to write edits, the file will be first clean (first "here") and then edited with with new data (second "here")

    You can ignore too fast reports (<1s) with a simple timer

    lastEdit = time.time()
    while True:
        if (state != os.path.getmtime('file.json')):
            state = os.path.getmtime('file.json')
            if time.time()-lastEdit > 1: 
                print('here')
            lastEdit = time.time()