Search code examples
pythonsymlink

os.symlink fails when directory exists and when directory doesn't exist


I have source and link paths. I'm trying to create a symlink, but must be misunderstanding how its used. Let's say

source = '/var/source/things/'
link = '/var/link/'

When I use os.symlink(source, link)

Initially I received an error

FileNotFoundError: [Errno 129] EDC5129I No such file or directory.: '/var/source/things/' -> '/var/link/'

Ok, so I'll put in something to create the directory if it doesn't exist.

if not os.path.exists(link):
    os.makedirs(link)

Re-run and now receive:

FileExistsError: [Errno 117] EDC5117I File exists.: '/var/source/things/' -> '/var/link/'

So if the directory doesn't exist it fails and if the directory does exist it also fails?

We have a bash script that uses

ln -sf $source/* $link

Which creates symlinks for all folders within 'source' and was hoping python would be just as easy. But as I mentioned before, I'm misunderstanding something here.


Solution

  • Can you remove "/" at the end under link and try once

    source = '/var/source/things/'
    link = '/var/link'
    

    apart from that, I don't see any issues in your code.