Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Is there a way to wait os.unlink() or os.remove() to finish?

I have the following code:

os.remove('_Temp_Dir_\main' + str(i) + '.exe')
os.rmdir('_Temp_Dir_')

Which gives me:

OSError: [WinError 145] Directory is not empty: '_Temp_Dir_'

if i put the line

time.sleep(0.05)

before os.rmdir(), it works correctly. I think os.remove() isn't fast enough to remove the file. Any way to wait for it to finish its work?

like image 403
user2803910 Avatar asked Sep 22 '13 09:09

user2803910


1 Answers

Use shutil.rmtree() to remove the directory and don't bother with removing the file:

import shutil

shutil.rmtree('_Temp_Dir_')

The os.remove() works just fine (it won't return until the file remove completes), there must be other files in that directory that the process left behind and are removed during your sleep() call.

like image 56
Martijn Pieters Avatar answered Sep 28 '22 12:09

Martijn Pieters