简体   繁体   中英

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM