您可以在os.O_CREAT |中使用
os.open os.O_EXCL
flags如果文件存在则会失败,它们是根据Unix和Windows上提供的文档但是我不确定Windows上是否存在原子文件创建:
os.open("filename", os.O_CREAT | os.O_EXCL)
O_EXCL
If O_CREAT and O_EXCL are set, open() shall fail if the file exists. The check for the existence of the file and the creation of the file if it does not exist shall be atomic with respect to other threads executing open() naming the same filename in the same directory with O_EXCL and O_CREAT set. If O_EXCL and O_CREAT are set, and path names a symbolic link, open() shall fail and set errno to [EEXIST], regardless of the contents of the symbolic link. If O_EXCL is set and O_CREAT is not set, the result is undefined.
如果文件存在,则不确定要执行的操作,但只需在文件已存在时捕获FileExistsError:
import os
def try_make_file(filename):
try:
os.open(filename, os.O_CREAT | os.O_EXCL)
return True
except FileExistsError:
return False