检查两个文件指针是否指向 Python 中的同一个文件

Check if two file pointers point to same file in Python

如何检查两个文件指针是否指向同一个文件。

>>> fp1 = open("/data/logs/perf.log", "r")
>>> fp1
<open file '/data/logs/perf.log', mode 'r' at 0x7f5adc07cc00>
>>> fp2 = open("/data/logs/perf.log", "r")
>>> fp2
<open file '/data/logs/perf.log', mode 'r' at 0x7f5adc07cd20>
>>> fp1 == fp2
False
>>> fp1 is fp2
False

我的用例是我正在观察一个文件的变化并做一些事情,但是 logback 将这个文件回滚到旧日期并创建一个新文件。但是 python 中的文件指针变量仍然指向旧文件。如果 fp1 != fp2,我想更新 fp1 到新文件。

为什么 .name 不起作用? 当我尝试时,

mv /data/logs/perf.log /data/logs/perfNew.log
echo abctest >> /data/logs/perfNew.log

即便如此,名字还是旧的

>>> fp1.readline()
'abctest\n'
>>> fp1.name
'/data/logs/perf.log'

os.fstat is available on Windows and UNIX, and comparing the inode number (file serial number) and device ID uniquely identify a file within the system:

import os
fp1 = open("/data/logs/perf.log", "r")
fp2 = open("/data/logs/perf.log", "r")
stat1 = os.fstat(fp1.fileno())
stat2 = os.fstat(fp2.fileno())

# This comparison tests if the files are the same
stat1.st_ino == stat2.st_ino and stat1.st_dev == stat2.st_dev

fp1.close()
fp2.close()

st_ino 是 inode 编号,它在驱动器上唯一标识文件。但是,相同的 inode 号可以存在于不同的驱动器上,这就是为什么 st_dev(设备 ID)用于区分文件在哪个 drive/disk/device 上的原因。