Why does os.symlink uses path relative to destination?


Python 3.7 doc for os.symlink(src, dst) is Create a symbolic link pointing to src named dst.

Let’s imagine this working directory :

+-- nb.ipynb
+-- dir1
|   +-- file1
+-- dir2

Let’s suppose I want to create a symbolic link in dir2 called filed2 pointing to dir1/file1 from my notebook nb.ipynb.

In a cell of the notebook, i’ll put:

import os
os.symlink('dir1/file1', 'dir2/file2')

However, this won’t work, this will create a file2 in dir2, but when you look at the properties of this file, its Type is Link(broken) (inode/symlink) and its Link target is dir1/file1. The Link target is what you put as src in os.symlink.
To achieve the right symlink, one would need to do

os.symlink('../dir1/file1', 'dir2/file2')

which means that os.symlink(src, dest), src should contain the path of the source relative to the destination.

Since I had to create such symlink multiple times, I created this function :

def symlink_rel(src, dst):
    rel_path_src = os.path.relpath(src, os.path.dirname(dst))
    os.symlink(rel_path_src, dst)


symlink_rel('dir1/file1', 'dir2/file2')

will create the right symbolic link. It does seem to me that os.symlink doesn’t behave like the documentation says so. Why does os.symlink need src to be path of src relative to dst rather than src and dst to be path from the working directory?

Asked By: Statistic Dean



os.symlink('dir1/file1', 'dir2/file2') 

Soft links saves the original location of the file which means "dir2/file2" saves the location "dir1/file1". When you cat the file "dir2/file2" this will search for the "dir1/file1" inside the directory "dir2/" which is the working directory of "file2" and there is no path inside the dir2 called "dir1/file1"

os.symlink('../dir1/file1', 'dir2/file2')

when you cat this file dir2/file2 , the parent directory of the "file2" is "dir2".
which is same as above. The difference is that ".." means go one directory from where you are standing right now. From that location goto "dir1/file1" so it will work.

Don’t consider your working directory, consider the softlinks parent
directory and read the location based on that

Answered By: Fuji Komalan
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.