Create broken symlink with Python

Mathias picture Mathias · Nov 19, 2009 · Viewed 10.4k times · Source

Using Python I want to create a symbolic link pointing to a path that does not exist. However os.symlink just complains about "OSError: [Errno 2] No such file or directory:".. This can easily be done with the ln program, but how to do it in Python without calling the ln program from Python?

Edit: somehow I really messed this up :/ ... both answers below is correct

Answer

Denis Otkidach picture Denis Otkidach · Nov 19, 2009

Such error is raised when you try to create a symlink in non-existent directory. For example, the following code will fail if /tmp/subdir doesn't exist:

os.symlink('/usr/bin/python', '/tmp/subdir/python')

But this should run successfully:

src = '/usr/bin/python'
dst = '/tmp/subdir/python'

if not os.path.isdir(os.path.dirname(dst)):
    os.makedirs(os.path.dirname(dst))
os.symlink(src, dst)