how to create a file and throw exception if already exists
Question: In my program, many processes can try to create a file if the file doesnt
exist currently. Now I want to ensure that only one of the processes is able
to create the file and the rest get an exception if its already been
created(kind of process safe and thread safe open() implementation). How can I
achieve this in python.

Just for clarity, what I want is that the file is created if it doesnt exist.
But if it already exists then throw an exception. And this all should happen
atomicly.


Answer: In Python 2.x:

    
    
    import os
    
    fd = os.open('filename', os.O_CREAT|os.O_EXCL)
    with os.fdopen(fd, 'w') as f:
        ....
    

In Python 3.3+:

    
    
    with open('filename', 'x') as f:
        ....
    

