Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easiest way to rm -rf in Python

Tags:

python

What is the easiest way to do the equivalent of rm -rf in Python?

like image 699
Josh Gibson Avatar asked May 02 '09 04:05

Josh Gibson


People also ask

How do you permanently delete a file in Python?

1. Using the os module in python. The os module allows you to use the operating system-dependent functionalities. To use the os module to delete a file, we import it, then use the remove() function provided by the module to delete the file.

How do I remove something from a list in Python?

How to Remove an Element from a List Using the remove() Method in Python. To remove an element from a list using the remove() method, specify the value of that element and pass it as an argument to the method. remove() will search the list to find it and remove it.


2 Answers

import shutil shutil.rmtree("dir-you-want-to-remove") 
like image 183
Josh Gibson Avatar answered Oct 26 '22 01:10

Josh Gibson


While useful, rmtree isn't equivalent: it errors out if you try to remove a single file, which rm -f does not (see example below).

To get around this, you'll need to check whether your path is a file or a directory, and act accordingly. Something like this should do the trick:

import os import shutil  def rm_r(path):     if os.path.isdir(path) and not os.path.islink(path):         shutil.rmtree(path)     elif os.path.exists(path):         os.remove(path) 

Note: this function will not handle character or block devices (that would require using the stat module).

Example in difference of between rm -f and Python's shutils.rmtree

$ mkdir rmtest $ cd rmtest/ $ echo "stuff" > myfile $ ls myfile $ rm -rf myfile  $ ls $ echo "stuff" > myfile $ ls myfile $ python Python 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53)  [GCC 4.5.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import shutil >>> shutil.rmtree('myfile') Traceback (most recent call last):   File "<stdin>", line 1, in <module>   File "/usr/lib/python2.7/shutil.py", line 236, in rmtree     onerror(os.listdir, path, sys.exc_info())   File "/usr/lib/python2.7/shutil.py", line 234, in rmtree     names = os.listdir(path) OSError: [Errno 20] Not a directory: 'myfile' 

Edit: handle symlinks; note limitations as per @pevik's comment

like image 38
Gabriel Grant Avatar answered Oct 26 '22 02:10

Gabriel Grant