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

标签 python file

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

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/

相关文章:

python - wxPython 网格中的自动换行和换行

python - pandas 按组填充多列

python - 包括 python 中的 ascii 艺术

java - 如何将图库中的图像作为文件参数

python - Numpy 数组均值函数在均值计算中未排除屏蔽元素

python - 用每列的一组平均值填充 NaN

c++ - C++从文件中读取对象

android - 无法检查 SD 卡上的文件是否存在

arrays - 如何在 Perl 中创建二维数组?

ajax - Chrome Beta 8 禁用 Google Chrome --allow-file-access-from-files