Race-condition creating folder in Python

后端 未结 5 1913
清酒与你
清酒与你 2021-01-04 02:20

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         


        
5条回答
  •  抹茶落季
    2021-01-04 02:35

    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)
    

提交回复
热议问题