How do I check if two file pointers point to the same file or not.
>>> 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
My use case is I am watching a file for changes and doing something, but logback rolls over this file to old date and creates a new file. But the file pointer variable in python is still pointing to the old file. If fp1 != fp2
, I would like to update fp1
to new file.
Why .name
doesn't work?
When I tried,
mv /data/logs/perf.log /data/logs/perfNew.log
echo abctest >> /data/logs/perfNew.log
even then the name still is the old one.
>>> 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
is the inode number which identifies the file uniquely on a drive. However, the same inode number can exist on different drives, which is why the st_dev
(device ID) is used to distinguish which drive/disk/device the file is on.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With