📜  Python – 获取 windows 文件的文件 ID

📅  最后修改于: 2022-05-13 01:55:15.983000             🧑  作者: Mango

Python – 获取 windows 文件的文件 ID

文件 ID是 Windows 上用于标识卷上唯一文件的唯一文件标识符。 File Id的工作原理与 *nix Distributions 中的 inode 编号类似。这样一个 fileId 可用于唯一标识卷中的文件。
我们将使用在Windows 命令处理器cmd.exe 中找到的命令来查找文件的 fileid。为了从Python访问/调用 cmd.exe,我们将使用 *os 库中的 popen()函数。
os 库预装到大多数Python发行版中。如果没有,可以通过在其操作系统的命令处理器中运行以下命令来安装该库:

pip install os

* 调用命令行时不必使用 os 库。也可以使用替代方法来调用命令行(例如 subprocess.popen() 也可以用于此目的)。
在本文中,我们将通过使用其路径来查询驱动器上文件的 fileId。然后稍后会使用这个fileId来获取文件的绝对路径。

Python3
# importing popen from the os library
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)


Python3
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)


输出:

File ID is 0x00000000000000000001000000000589

现在我们将使用该文件的 fileid 来获取卷中文件的路径。

Python3

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)

输出:

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

其中 C:\Users\Grandmaster\Desktop\testing.py 是文件的路径
解释:
这两个程序的核心在于语句 popen(fr”fsutil file queryfileid {file}”) 和 popen(fr”fsutil file querfyfilenamebyid C:\ {fileid}”)。其中的解释是:-

  • 命令中的术语 fsutil 是 Windows 命令处理器中的一个命令,用于执行文件和卷特定命令、硬链接管理、USN 日志管理、对象 ID 和重解析点管理。
  • 第一个参数(到 fsutil)file 用于访问文件系统中的文件特定选项。存在其他参数,例如 USN 用于在USN Journal上执行操作, hardlink用于在文件系统的硬链接上执行操作。
  • 第二个参数 queryfileid 用于获取第四个参数中提供的路径名的 fileId。如果在作为第四个参数提供的路径中找不到此文件,则会显示否定消息错误:系统找不到指定的文件。被退回。如果文件存在于提供的路径中,则该命令返回文件的 fileId。
  • 在第二个代码中,第二个参数是 queryfilenamebyid,它的工作方式与 queryfileid 相反。它将 Volume 作为与 fileId 关联的文件所在的第三个参数。作为第四个参数,它接受 fileId 并返回具有该 fileId 的文件在该卷中所在的路径。