Search code examples
pythonos.path

os.path.getmtime when file doesn't exist


How do I set a variable to None or null when the file doesn't exist for example:

lastModified = os.path.getmtime("/xyz.csv") if os.path.getmtime("/xyz.csv") is not None else null

So I would like lastModified variable to be the time the file was last modified when the file exists else to be null when it doesn't exist.

Any


Solution

  • Use exists function from os.path module:

    from os.path import getmtime, exists
    
    file_path = './file.txt'
    last_mod = getmtime(file_path) if exists(file_path) else None
    print(last_mod)