user5359531
user5359531

Reputation: 3555

"No such file" error trying to get modification time for symlink

I am trying to get the modification time of files on my hard drive. The code looks like this:

mtime = int(os.path.getmtime(path))

However, I keep running into this strange error:

File "./import.py", line 67, in find
  mtime = int(os.path.getmtime(path))
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/genericpath.py", line 62, in getmtime
  return os.stat(filename).st_mtime
OSError: [Errno 2] No such file or directory: '/Users/username/Library/Application Support/Google/Chrome/RunningChromeVersion'

This is strange because the item does exist; its a symlink to the version of Chrome that is installed:

$ ll '/Users/username/Library/Application Support/Google/Chrome/RunningChromeVersion'
lrwxr-xr-x@ 1 username  staff    13B Jan 12 16:58 /Users/username/Library/Application Support/Google/Chrome/RunningChromeVersion -> 79.0.3945.117

Notably, it indeed has a modification time; Jan 12 16:58

However, if you get the absolute path, it looks like this:

$ greadlink -f '/Users/username/Library/Application Support/Google/Chrome/RunningChromeVersion'
/Users/username/Library/Application Support/Google/Chrome/79.0.3945.117

and if you check, that target does not actually exist;

$ ll '/Users/username/Library/Application Support/Google/Chrome/79.0.3945.117'
ls: /Users/username/Library/Application Support/Google/Chrome/79.0.3945.117: No such file or directory

What I do not understand, is why is Python not returning the modification time of the symlink, the path its actually being given? Why does this cause an error at all? Obviously ls is able to see the modification time, so why cant Python figure it out?

Upvotes: 0

Views: 318

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295619

To get stat data on the link itself rather than its target, use os.lstat() rather than os.stat().

Upvotes: 2

Related Questions