Get unique id of file a in a system using python

Get unique id of file a in a system using python

Problem Description:

I m trying to find the unique id of a file which does not change upon modification of file or changing anything which works in multiOS.
I cant use the name, path, file content hash as it can be modified.

I tried using inode id, st_ctime_ns but it changes.
I need to monitor the file using the id of file system generated.

Changing on file modification:

file_uid = os.stat(file).st_ctime_ns

Changing if reran on another function

file_uid = os.stat(filename).st_ino

Does not work in unix

file_uid = popen(fr"fsutil file queryfileid {file}").read()

Solution – 1

The only real unique identifier would be the creation date, and sadly on some systems it’s not available (ctime is the last modified date on Linux).

So this is your best bet:
As long as the file is unmodified it will have the same id on Linux.

Code snippet from Mark Amery:

import os
import platform

def creation_date(path_to_file):
    Try to get the date that a file was created, falling back to when it was
    last modified if that isn't possible.
    See for explanation.
    if platform.system() == 'Windows':
        return os.path.getctime(path_to_file)
        stat = os.stat(path_to_file)
            return stat.st_birthtime
        except AttributeError:
            # We're probably on Linux. No easy way to get creation dates here,
            # so we'll settle for when its content was last modified.
            return stat.st_mtime
Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.