How to create a file and throw an exception if it already exists

In my program, many processes may try to create a file if the file does not currently exist. Now I want to make sure that only one of the processes is able to create the file, and the rest will get an exception if it has already been created (view of a safe process and implementation of open safe). How can I achieve this in python.

Just for clarity, I want the file to be created if it does not exist. But if it already exists, it throws an exception. And all this should happen atomically.

+6
source share
2 answers

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: .... 
+6
source

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.

+4
source

Source: https://habr.com/ru/post/948491/


All Articles