【问题标题】:Get unique id of file a in a system using python使用python获取系统中文件a的唯一ID
【发布时间】:2022-12-05 17:22:02
【问题描述】:

我试图找到一个文件的唯一 ID,该 ID 在修改文件或更改在 multiOS 中有效的任何内容时都不会更改。 我不能使用名称、路径、文件内容哈希,因为它可以被修改。

我尝试使用 inode id, st_ctime_ns 但它改变了。 我需要使用生成的文件系统的 ID 来监视文件。

更改文件修改:

file_uid = os.stat(file).st_ctime_ns

如果在另一个函数上重新运行则更改

file_uid = os.stat(filename).st_ino

在 unix 中不起作用

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

【问题讨论】:

  • 你不能使用创建日期吗?
  • 这似乎不是编程问题。有关操作系统/文件系统相关问题的问题应该在我们的兄弟站点之一中提出。
  • 不完全确定,但文件校验和可能对您有帮助
  • @Nineteendo 创建日期在修改文件时会发生变化,如果用户使用脚本创建了多个文件,或者 id 是唯一的,该怎么办?

标签: python


【解决方案1】:

唯一真正的唯一标识符是创建日期,遗憾的是在某些系统上它不可用(ctime 是 Linux 上的最后修改日期)。

所以这是你最好的选择:https://stackoverflow.com/a/39501288/13454049 只要文件未修改,它在 Linux 上就会有相同的 ID。

来自 Mark Amery 的代码 sn-p:

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 http://stackoverflow.com/a/39501288/1709587 for explanation.
    """
    if platform.system() == 'Windows':
        return os.path.getctime(path_to_file)
    else:
        stat = os.stat(path_to_file)
        try:
            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

【讨论】:

    猜你喜欢
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-21
    相关资源
    最近更新 更多