编辑 :另请参见DaveJones的回答:从Python3.3开始,您可以使用该
x标志
open()来提供此功能。
作为参考,Python 3.3
'x'在
open()函数中实现了一种新模式来涵盖此用例(仅创建,如果文件存在则失败)。请注意,
'x'模式是单独指定的。使用
'wx'结果中的
ValueErroras
'w'是多余的(无论如何,如果调用成功,您唯一可以做的就是将其写入文件;如果调用成功,它就不存在):
>>> f1 = open('new_binary_file', 'xb')>>> f2 = open('new_text_file', 'x')下面的原始答案
是的,但不使用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 osimport errnoflags = os.O_CREAT | os.O_EXCL | os.O_WRONLYtry: 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. raiseelse: # 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!")


