编辑:另请参见Dave Jones的回答:从Python 3.3开始,您可以使用该x标志open()来提供此功能。
下面的原始答案
是的,但不使用Python的标准open()调用。您将需要使用os.open()代替,它允许您为基础C代码指定标志。
特别是您要使用O_CREAT | O_EXCL。从该名男子页open(2)下O_EXCL我的Unix系统:
确保此调用创建了文件:如果将此标志与一起指定O_CREAT,并且路径名已经存在,open()则将失败。O_EXCL如果O_CREAT未指定,则行为不确定。
当指定了这两个标志时,将不遵循符号链接:如果pathname是符号链接,则open()无论符号链接指向何处都将失败。
O_EXCL 仅当在内核2.6或更高版本上使用NFSv3或更高版本时,NFS才支持该功能。在O_EXCL不提供NFS 支持的环境中,依赖它执行锁定任务的程序将包含竞争条件。
因此它并不完美,但是AFAIK是避免这种情况的最接近的方法。
编辑:使用os.open()而不是其他规则open()仍然适用。特别是,如果你想使用返回的文件描述符进行读取或写入,你需要的一个O_RDONLY,O_WRONLY或O_RDWR标志以及。
所有O_*标志都在Python的os模块中,因此您需要import os使用os.O_CREAT等。
例:
import os
import errno
flags = os.O_CREAT | os.O_EXCL | os.O_WRONLY
try:
file_handle = os.open('filename', flags)
except OSError as e:
if e.errno == errno.EEXIST: # Failed as the file already exists.
pass
else: # Something unexpected went wrong so reraise the exception.
raise
else: # No exception, so the file must have been created successfully.
with os.fdopen(file_handle, 'w') as file_obj:
# Using `os.fdopen` converts the handle to an object that acts like a
# regular Python file object, and the `with` context manager means the
# file will be automatically closed when we're done with it.
file_obj.write("Look, ma, I'm writing to a new file!")