Can't delete / unlink a symlink to directory in python & windows
Asked Answered
F

2

3

edited

i created symlinks to a directory, on Widnows7, using mklink command line:

mklink /d books config

i'm trying to delete it with python 2.7 (still on windows).

>>> os.remove('books')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    sym = symlink_to_dir
    os.unlink(sym) # 
WindowsError: [Error 5] Access is denied: 'books'

there are no restrictions on that machine, i'm admin, and i didn't have problems to delete it from Windows (del books)

There's no problem deleting a link to a file (as opposed to a dir).

why is that?

edit "del" didn't work, it just didn't return an error.

Finesse answered 24/10, 2014 at 18:34 Comment(4)
What does "there are no permissions on that machine" mean? Taken literally, it makes the answer pretty obvious: if you have no permissions, you should be getting access denied for everything. But I can't figure out any way to take it that makes more sense…Married
Meanwhile, any chance the symlink is in use? For example have you cd'd to the symlink (or a subdirectory through the symlink) in a running cmd.exe shell?Married
One last thing: You almost certainly don't want os.system('del '+sym). That gives you no way to tell whether it succeeded or failed, it will not work if sym has any spaces or various other special characters, etc. If you really need to run an external command, use subprocess, not os.system.Married
Also, is 'static' the name of the file?Married
F
4

oops, i overlooked it:

since it's a link to a directory, windows, unlike linux, consider the symlink as a directory, therefore:

from DOS:

c:\> rmdir symlink

from python:

>>> os.rmdir( 'symlink' )

and NOT "del symlink", nor "os.unlink()", nor "os.remove()".

This is how it looks like in Linux:

$ mkdir a
$ ln -s a b
$ rm b          #ok, since a symlink is treated as a file

$ ln -s a b
$ rmdir b       # error, not a file
rmdir: failed to remove `b': Not a directory
Finesse answered 25/10, 2014 at 8:54 Comment(1)
Yes, os.rmdir() is the correct way to remove a symlink to a directory on Windows. I can confirm that the contents of the original directory won't be removed.Lipp
D
1

I will make a guess. What you have may not be a symlink like the ones on *INX, but rather a hard link. You should be able to os.remove() to remove the hard link.

Debrahdebrecen answered 24/10, 2014 at 19:3 Comment(1)
Was about to say this when you responded. We need to know what options were used during mklink!Solano

© 2022 - 2024 — McMap. All rights reserved.