Can't delete / unlink a symlink to directory i

2019-05-20 21:26发布

问题:

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.

回答1:

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


回答2:

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.