Delete a directory that is not empty on python -


so, need clean directory not empty. have created following function.for testing reasons tried remove jdk installation

def clean_dir(location):     filelist = os.listdir(location)      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 use rmtree , rmdir, fails.

the error got using rmtree is:

oserror: cannot call rmtree on symbolic link

and error got when used rmdir:

oserror: [errno 66] directory not empty: '/tmp/jdk1.8.0_25/jre/lib/amd64/server'

the code works correctly on windows. reason fails on linux.

you're encountering 1 of differences between way windows , linux (unix really) handle filesystems. believe adding additional case code @ least help:

... filename in filelist:     fullpath = os.path.join(location, filename)     ## |<-- handle symlink -->|     if os.path.islink(fullpath) or os.path.isfile(fullpath):         os.chmod(fullpath, stat.s_irwxu | stat.s_irwxg | stat.s_irwxo)         os.remove(os.path.join(location, filename))     elif os.path.isdir(fullpath):         if len(os.listdir(fullpath)) > 0:             clean_dir(fullpath)         #os.rmdir(os.path.join(location, filename))         shutil.rmtree(os.path.join(location, filename)) ... 

this should handle case entry symlink , remove file. i'm not sure chmod necessary - works on target of link, shouldn't hurt handle same way file.

however, checked , os.path.file against symbolic link returns type of "thing" pointed to, additional check needed differentiate between link , thing pointed to. portable, instead of appending "/" use os.path.join newly edited above.


Comments

Popular posts from this blog

javascript - Slick Slider width recalculation -

jsf - PrimeFaces Datatable - What is f:facet actually doing? -

angular2 services - Angular 2 RC 4 Http post not firing -