If you are running a Unix-like system, open the file as follows:
f = os.fdopen(os.open(filename, os.O_CREAT | os.O_WRONLY | os.O_EXCL), 'w')
The O_EXCL flag on os.open ensures that a file will be created (and opened) only if it does not already exist, otherwise an OSError exception will be OSError . Checking for existence and creation will be performed atomically, so you can have several threads or processes that try to create a file, and only one of them will succeed.
source share