Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 952
Adobri Avatar asked Jul 01 '13 18:07

Adobri


People also ask

Which method is to create a new content if the file does not exist or replace with the new content in case of file existing?

Sometimes, you may want to delete the content of a file and replace it entirely with new content. You can do this with the write() method if you open the file with the "w" mode.

How do you create a file if it doesn't exist in Python?

If a file does not exist in your system, you can use the open() method to create one. The open() method takes the file path and mode as input and outputs a file object.

Which of the following does not create a new file if the file is not found in the directory?

open() in Python does not create a file if it doesn't exist.


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:
    ....
like image 184
falsetru Avatar answered Oct 10 '22 11:10

falsetru


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.

like image 45
user4815162342 Avatar answered Oct 10 '22 11:10

user4815162342