Python – Get file id of windows file

File ID is a unique file identifier used on windows to identify a unique file on a Volume. File Id works similar in spirit to a inode number found in *nix Distributions. Such that a fileId could be used to uniquely identify a file in a volume.

We would be using an command found in Windows Command Processor cmd.exe to find the fileid of a file. In order to access/invoke cmd.exe from python, we would be using popen() function found in the *os library.

os library is preinstalled into most python distributions. If not, one can install the library by running the following command in the command processor of their operating system:

pip install os

* It is not necessary to use only os library for the purpose of invoking the command line. One could also use alternatives for invoking the commandline (ex. subprocess.popen() could also be used for the purpose).

In this article, we will query fileId of a file on our drive, by using its path. And then later would use this fileId to obtain the absolute path to the file.



filter_none

edit
close

play_arrow

link
brightness_4
code

# importing popen from the os libary
from os import popen
  
# Path to the file whose id we would
# be obtaining (relative / absolute)
file = r"C:\Users\Grandmaster\Desktop\testing.py"
  
# Running the command for obtaining the fileid,
# and saving the output of the command
output = popen(fr"fsutil file queryfileid {file}").read()
  
# printing the output of the previous command
print(output)

chevron_right


Output:

File ID is 0x00000000000000000001000000000589

Now we would be using the fileid of this file to obtain the path to the file in the volume.

filter_none

edit
close

play_arrow

link
brightness_4
code

from os import popen
  
# Fileid of the file
fileid = "0x00000000000000000001000000000589"
  
# Running the command for obtaining the file path, 
# of the file associated with the fileid
output = popen(fr"fsutil file queryfilenamebyid C:\ {fileid}").read()
  
print(output)

chevron_right


Output:

A random link name to this file is \\?\C:\Users\Grandmaster\Desktop\testing.py

Where C:\Users\Grandmaster\Desktop\testing.py is the path to the file

Explanation:

The core of both the programs lies in the statements popen(fr"fsutil file queryfileid {file}") and popen(fr"fsutil file querfyfilenamebyid C:\ {fileid}"). The explanation of which is:-