How To Delete The Symlink Along With The Source Directory
I would like to delete the symlink along with the source directory. For example - ls -lrt testsymlink -> /user/temp/testdir I would like to remove both testsymlink and /user/
Solution 1:
You can use the result of os.path.realpath
to detect and delete the symlink target. Example:
import os
# ./foo -> ./bar
filepath = "./foo"
if (os.path.realpath(filepath) != filepath):
targetpath = os.path.realpath(filepath)
os.remove(filepath)
if (targetpath):
os.remove(targetpath)
Solution 2:
EDIT: I didn't see that you wanted a solution in python: This is all only relevant in a unix shell. Although you could wrap the two commands below in a os.system()
call, I highly suggest you follow Tim's answer.
To get the path of the object the symlink is pointing to, you can use readlink
:
$ readlink testsymlink
/user/temp/testdir
To delete the object the symlink is pointing to, you can pass the output of readlink
to rm
:
$ rm -r `readlink testsymlink`
The backticks cause the command inside of them to be run, and then replaced with its own output. Finally, to remove the symlink itself, we simply run:
$ rm testsymlink
Post a Comment for "How To Delete The Symlink Along With The Source Directory"