1

The standard way of deleting folders in python I am aware of is

 shutil.rmtree('/path/to/folder')

However, this command blocks until the deletion is completed, which in the case of large folders can take a long time.

Is there a non-blocking alternative? I.e. a function that would delete the folder in the 'background' but return immediately?

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
Arco Bast
  • 3,595
  • 2
  • 26
  • 53

1 Answers1

4

Since most of the time spent is spent in system calls, a thread can help

import threading,shutil

threading.Thread(target = lambda : shutil.rmtree('/path/to/folder')).start()

that is the shortest way. Maybe a better way would be to create a proper function so the call can be wrapped in a try/except block. Alternatives here: Deleting folders in python recursively

Another alternative would be to call a system command like rm in the background but that is not very portable, even if this would be faster, but only slightly since most of the time is spent in the operating system anyway.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
  • Would I do `os.system('rm -r /path/to/folder &')`? Do you know how the performance compares between `rm`and `shutil`? – Arco Bast Mar 31 '20 at 20:14
  • 1
    I'd say rm would be _slightly_ faster. And also simpler to implement specially with `-f` option. shutil can choke on protected files if not properly configured. But running a system command to delete a file is really overkill and bad practice in python – Jean-François Fabre Mar 31 '20 at 20:42
  • thanks! well, you mention mostly advantages of `rf`. let's assume it would be guaranteed that the code is executed on a platform that provides `rf` - would you still consider its usage bad practice? if so, why? – Arco Bast Mar 31 '20 at 22:34
  • 1
    if your script runs on unix/linux and will never be ported anywhere you can use a `rm` system call. I personally never assume that my scripts won't be ported. – Jean-François Fabre Apr 01 '20 at 07:17