I have a urllib2 caching module, which sporadically crashes because of the following code:
if not os.path.exists(self.cache_location):
os.mkdir(self.cach
In Python 3.x, you can use os.makedirs(path, exist_ok=True)
, which will not raise any exception if such directory exists. It will raise FileExistsError: [Errno 17]
if a file exists with the same name as the requested directory (path
).
Verify it with:
import os
parent = os.path.dirname(__file__)
target = os.path.join(parent, 'target')
os.makedirs(target, exist_ok=True)
os.makedirs(target, exist_ok=True)
os.rmdir(target)
with open(target, 'w'):
pass
os.makedirs(target, exist_ok=True)