Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if two file pointers point to same file in Python

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'
like image 954
Optimus Prime Avatar asked Sep 12 '18 08:09

Optimus Prime


1 Answers

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.

like image 87
Alex Taylor Avatar answered Sep 19 '22 14:09

Alex Taylor