gpt4 book ai didi

python - python 的 tempfile.mkstemp 总是产生唯一的名称吗?

转载 作者:行者123 更新时间:2023-12-01 05:54:42 24 4
gpt4 key购买 nike

我正在自动生成文件名,并且我不希望发生覆盖。我正在懒惰地使用这一小行代码

fd, filepath = tempfile.mkstemp(ext, prefix='odt_img_', dir=self.destPath)
os.close(fd) # just using the name and overwriting later

后来我写入文件路径,但我不确定 mkstemp 是否只是添加一些随机字母,或者它是否确实确保名称是唯一的。

最佳答案

tempfile.mkstemp 仅保证创建并打开名称不存在的新文件。来自 docs :

Creates a temporary file in the most secure manner possible. There are no race conditions in the file’s creation, assuming that the platform properly implements the os.O_EXCL flag for os.open().

并且 O_EXCL 标志指定:

Ensure that this call creates the file: if this flag is specified in conjunction with O_CREAT, and the filename already exists, then open() will fail.

在内部,mkstemp 只是循环遍历一个随机序列,尝试创建一个不存在的文件,直到成功或用完“想法”,在这种情况下,它会失败并出现 IOError。

关于python - python 的 tempfile.mkstemp 总是产生唯一的名称吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13101437/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com