[Tutor] os.symlink can't find target

Peter Otten __peter__ at web.de
Mon Feb 24 17:36:16 CET 2014


Bob Williams wrote:

> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
> 
> My operating system is Linux (openSUSE 13.1).
> 
> I'm trying to create symlinks. The following code:
> 
> if pathList[j][-3:] == "mp3":
>     linkName1 = pathList[j][0:-3] + "mp3"
>     linkName2 = destPath + linkName1[len(sourcePath):]
>     print 'Creating link %s -> %s' % (linkName2, pathList[j])
>     os.symlink(pathList[j], linkName2)
> 
> fails with this error:
> 
> 
> Creating link /pollux/music/portable/testing/artists/Death in
> June/1995 Rose Clouds Of Holocaust/10 Lifebooks.mp3 ->
> /home/bob/music/artists/Death in June/1995 Rose Clouds Of Holocaust/10
> Lifebooks.mp3
> Traceback (most recent call last):
>   File "/home/bob/Documents/scripts/python/flac2mp3.py", line 101, in
> <module>
>     os.symlink(pathList[j], linkName2)
> OSError: [Errno 2] No such file or directory
> 
> The same thing happens in ipython, when I type the paths in manually.
> I have tried escaping the spaces with '\', but the same error is
> generated.
> 
> The file "/home/bob/music/artists/Death in June/1995 Rose Clouds Of
> Holocaust/10 Lifebooks.mp3" definitely exists.
> 
> Thanks,

os.symlink(existing_file, symlink_to_create)

fails with that error if the directory that shall contain the new symlink 
does not exist. You can create it before making the symlink with

try:
    os.makedirs(os.path.dirname(symlink_to_create))
except OSError as err:
    # Assume the directory exists.
    # A thorough coder would check the errno here
    pass



More information about the Tutor mailing list