Python can't open symlinked file
Any ideas what I am doing wrong?
The target of the symbolic link doesn't exist.
I don't understand why I was able to resolve it in the ls statement in my question.
You weren't.
The ls
command by default operates on the link itself, not on the target of the link. Absent the -L
option, ls
never attempts to resolve the symbolic link.
Consider a directory with these two files:
$ ls -l
-rw-rw-r-- 1 me me 6 May 13 11:58 a
lrwxrwxrwx 1 me me 3 May 13 12:00 b -> ./a
a
is a text file containing the six bytes 'hello\n'
. b
is a link file containing the three bytes to its target path: './a'
. ls
is able to describe the properties of the link without dereferencing the link itself.
In contrast, use the -L
option:
$ ls -lL
-rw-rw-r-- 1 me me 6 May 13 11:58 a
-rw-rw-r-- 1 me me 6 May 13 11:58 b
Now ls
has resolved the link in b
, and displays information about the linked-to file. With -L
, ls
now claims that b
is also a six-byte text file.
Finally, consider this:
$ rm a
$ ls -l
lrwxrwxrwx 1 me me 3 May 13 12:00 b -> ./a
$ ls -lL
ls: cannot access b: No such file or directory
l????????? ? ? ? ? ? b
Now b
is a link that resolves to a file that no longer exists. Since ls -l
never attempts the resolve the link, its output is unchanged from the previous test. (b
is a link file, 3 bytes long, contents './a'
.)
But ls -lL
attempts to resolve the link, fails, and displays the failure information.