So, I need to clean a directory that is not empty. I have created the following function.For testing reasons I tried to remove a JDK installation
def clean_dir(location):
fileList = os.listdir(location)
for fileName in fileList:
fullpath=os.path.join(location, fileName)
if os.path.isfile(fullpath):
os.chmod(fullpath, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)
os.remove(location + "/" + fileName)
elif os.path.isdir(fullpath):
if len(os.listdir(fullpath)) > 0:
clean_dir(fullpath)
#os.rmdir(location + "/" + fileName)
shutil.rmtree(location + "/" + fileName)
return
I tried to use rmtree and rmdir, but it fails.
The error I got using rmtree is:
OSError: Cannot call rmtree on a symbolic link
And this is the error I got when I used rmdir:
OSError: [Errno 66] Directory not empty: '/tmp/jdk1.8.0_25/jre/lib/amd64/server'
The code works correctly on windows. But for some reason it fails on linux.
os.unlink(...)is all you need. (To clarify, that will just remove the symbolic link. It won't delete anything the symbolic link points to.)os.unlinkshould delete files as well.