Adobri
Adobri

Reputation: 481

how to create a file and throw exception if already exists

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.

Upvotes: 8

Views: 2984

Answers (2)

user4815162342
user4815162342

Reputation: 155366

If you're running on a Unix-like system, open the file like this:

f = os.fdopen(os.open(filename, os.O_CREAT | os.O_WRONLY | os.O_EXCL), 'w')

The O_EXCL flag to os.open ensures that the file will only be created (and opened) if it doesn't already exist, otherwise an OSError exception will be raised. The existence check and creation will be performed atomically, so you can have multiple threads or processes contend to create the file, and only one will come out successful.

Upvotes: 4

falsetru
falsetru

Reputation: 369394

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:
    ....

Upvotes: 10

Related Questions