0

Say I have 2 paths:

derp.py
/lol/lel/doge/derp.py

How do I check if both paths refer to the same file? I've seen two ways to do it, but are there any disadvantages to either.

os.path.samefile("derp.py", "/lol/lel/doge/derp.py")
os.path.abspath("derp.py") == os.path.abspath("/lel/lol/doge/derp.py")

I don't particularly care about following symlinks or if one of the files doesn't exist.

hifkanotiks
  • 5,915
  • 1
  • 17
  • 24
  • 1
    First you have to define "equality of files". The same contents? Or literally the *same* file (Symlinked)? – Sinkingpoint Feb 09 '14 at 08:31
  • I don't mind whether you compare the contents, or the symlinks, or just the path (without symlinks), I think all of those would work for me. However, a description of the advantages and disadvantages of the methods would be good. – hifkanotiks Feb 09 '14 at 08:37
  • 1
    What do you mean "don't care if one of the files doesn't exist" - what should happen in this case? What should happen if *neither* file exists? – Karl Knechtel Feb 09 '14 at 08:42
  • This might help: http://stackoverflow.com/questions/3212712/how-to-find-target-path-of-link-if-the-file-is-a-link-file – Novin Shahroudi Feb 09 '14 at 08:45
  • @KarlKnechtel If one of them doesn't exist, then the files aren't the same, of course! (But one of them should always exist.) – hifkanotiks Feb 09 '14 at 08:57

2 Answers2

2

If you don't care if any of the files exists, then os.path.samefile() will not work for you, because it actually compares i-node numbers. That leaves you with the only option of comparing the absolute paths.

bereal
  • 32,519
  • 6
  • 58
  • 104
0

The former adheres to symlinks, while the latter doesn't. using samefile is the "correct" way if your intention is that these files are the same file. If you just want to check that the paths point at the same place (disregarding symlinks) you can use the latter.

abyx
  • 69,862
  • 18
  • 95
  • 117