Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting read-only directory in Python

shutil.rmtree will not delete read-only files on Windows. Is there a python equivalent of "rm -rf" ? Why oh why is this such a pain?

like image 628
kevin cline Avatar asked Dec 11 '09 17:12

kevin cline


People also ask

How do I remove a specific directory in Python?

Deleting file/dir using the os. os. rmdir() method in Python is used to remove or delete an empty directory. OSError will be raised if the specified path is not an empty directory.

How do you delete a read only file?

Use the Properties Menu to Eliminate the Read Only Attribute. Right-click the file in Windows Explorer. Choose "Properties" from the drop-down menu. Uncheck the box next to the "Read Only" option in the "Properties" menu.


1 Answers

shutil.rmtree can take an error-handling function that will be called when it has problem removing a file. You can use that to force the removal of the problematic file(s).

Inspired by http://mail.python.org/pipermail/tutor/2006-June/047551.html and http://techarttiki.blogspot.com/2008/08/read-only-windows-files-with-python.html:

import os import stat import shutil  def remove_readonly(func, path, excinfo):     os.chmod(path, stat.S_IWRITE)     func(path)  shutil.rmtree(top, onerror=remove_readonly) 

(I haven't tested that snippet out, but it should be enough to get you started)

like image 98
Steve Losh Avatar answered Oct 16 '22 17:10

Steve Losh