Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shutil.rmtree to remove readonly files

Tags:

I want to use shutil.rmtree in Python to remove a directory. The directory in question contains a .git control directory, which git marks as read-only and hidden.

The read-only flag causes rmtree to fail. In Powershell, I would do "del -force" to force removal of the read-only flag. Is there an equivalent in Python? I'd really rather not walk the whole tree twice, but the onerror argument to rmtree doesn't seem to retry the operation, so I can't use

def set_rw(operation, name, exc):
    os.chmod(name, stat.S_IWRITE)

shutil.rmtree('path', onerror=set_rw)
like image 968
Paul Moore Avatar asked Jan 21 '14 14:01

Paul Moore


People also ask

Does Shutil Rmtree remove the directory?

Shutil rmtree() to Delete Non-Empty DirectoryThe rmtree('path') deletes an entire directory tree (including subdirectories under it). The path must point to a directory (but not a symbolic link to a directory). Set ignore_errors to True if you want to ignore the errors resulting from failed removal.

What is the use of Rmtree ()?

rmtree() is used to delete an entire directory tree, path must point to a directory (but not a symbolic link to a directory). Parameters: path: A path-like object representing a file path.

How to remove directory recursively in Python?

Path. rmdir() to delete an empty directory and shutil. rmtree() to recursively delete a directory and all of it's contents.


1 Answers

After more investigation, the following appears to work:

def del_rw(action, name, exc):
    os.chmod(name, stat.S_IWRITE)
    os.remove(name)
shutil.rmtree(path, onerror=del_rw)

In other words, actually remove the file in the onerror function. (You might need to check for a directory in the onerror handler and use rmdir in that case - I didn't need that but it may just be something specific about my problem.

like image 123
Paul Moore Avatar answered Dec 28 '22 14:12

Paul Moore