How to delete the symlink along with the source directory

那年仲夏 提交于 2019-12-23 20:54:05

问题


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/temp/testdir. Consider that I know the only the symlink name.

Any utility with python will do great.


回答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)



回答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


来源:https://stackoverflow.com/questions/12678205/how-to-delete-the-symlink-along-with-the-source-directory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!