Check if two file pointers point to same file in Python

  • A+
Category:Languages

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/doubleverify_logs/test.txt' 

 


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())  stat1.st_ino == stat2.st_ino and stat1.st_dev == stat2.st_dev 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: