Search code examples
pythonstat

How to stop pathlib.Path().stat() from resolving a symlink?


I want to test modification time of a file I have:

$ /tmp/bla -> bla.1 # was linked once
$ /tmp/bla.1        # was modified after the link

Now, if I run the shell command stat bla, I get one time, and stat bla.1 will give me a later time (because the link indeed was created once, but the destination was modified after that)

When doing it from python, it returns the same values for both the link and the destination because for some reason, it resolves the link:

In [1]: from pathlib import Path

In [2]: Path("bla").stat().st_mtime == Path("bla.1").stat().st_mtime
Out[2]: True

This is clearly wrong:

$ stat bla | grep "^Mod"
Modify: 2022-04-25 19:37:23.697182669 +0300
$ stat bla.1 | grep "^Mod"
Modify: 2022-04-25 19:37:59.437309050 +0300

pathlib.Path.stat says that:

Return the result of the stat() system call on this path, like os.stat() does.

but it doesn't help me because it also resolves the link. How can this be fixed? (Same issue with os.stat)

Python3.6.9


Solution

  • Like the documentation for this method already tells you, use lstat if you don't want symlinks resolved.