Check if two file pointers point to same file in Python
Asked Answered
A

1

13

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'
Ahasuerus answered 12/9, 2018 at 8:52 Comment(5)
related: #23156774Cosy
@Jean-FrançoisFabre Question seems related but there is no accepted answer, and doesn't solve my use case.Ahasuerus
@OptimusPrime There is an accepted answer claiming that you cannot use comparison for file handles. That is how I read it anyway.Rachealrachel
I could have closed as duplicate and I didn't. Hence related not duplicate. The fstat answer below works (beat me by a few minutes damn :))Cosy
@Jean-FrançoisFabre sorry, misread your commentAhasuerus
P
18

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.

Petrarch answered 12/9, 2018 at 9:9 Comment(3)
Please close fp1 and fp2 ;)Afterimage
@EricDuminil Isn't it okay if I just close one?Ahasuerus
@OptimusPrime: No, you need to make sure every file handle is closed.Afterimage

© 2022 - 2024 — McMap. All rights reserved.