问题描述
当前,我有一个循环,试图通过在文件名字符串中添加后缀来查找未使用的文件名.一旦找不到文件,它将使用无法以该名称打开新文件的名称.问题在于此代码在网站中使用,并且可能同时尝试多次执行同一操作,因此存在竞争条件.
Currently I have a loop that tries to find an unused filename by adding suffixes to a filename string. Once it fails to find a file, it uses the name that failed to open a new file wit that name. Problem is this code is used in a website and there could be multiple attempts to do the same thing at the same time, so a race condition exists.
如果在检查时间和另一个线程中的打开时间之间创建了一个文件,如何防止python覆盖现有文件.
How can I keep python from overwriting an existing file, if one is created between the time of the check and the time of the open in the other thread.
我可以通过对后缀进行随机化来最小化机会,但是根据路径名的一部分,机会已经被最小化了.我想通过一个可以告诉您的函数来消除这种机会,仅在不存在的情况下创建此文件.
I can minimize the chance by randomizing the suffixes, but the chance is already minimized based on parts of the pathname. I want to eliminate that chance with a function that can be told, create this file ONLY if it doesn't exist.
我可以使用win32函数来执行此操作,但是我希望它可以跨平台工作,因为它将最终托管在linux上.
I can use win32 functions to do this, but I want this to work cross platform because it will be hosted on linux in the end.
推荐答案
使用 os.open()
和os.O_CREAT
和os.O_EXCL
创建文件.如果文件已经存在,那将失败:
Use os.open()
with os.O_CREAT
and os.O_EXCL
to create the file. That will fail if the file already exists:
>>> fd = os.open("x", os.O_WRONLY | os.O_CREAT | os.O_EXCL)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OSError: [Errno 17] File exists: 'x'
创建新文件后,请使用 os.fdopen()
将句柄变成标准的Python文件对象:
Once you've created a new file, use os.fdopen()
to turn the handle into a standard Python file object:
>>> fd = os.open("y", os.O_WRONLY | os.O_CREAT | os.O_EXCL)
>>> f = os.fdopen(fd, "w") # f is now a standard Python file object
从Python 3.3开始,内置的 open()
具有x
模式,表示打开以进行独占创建,如果文件已存在则失败".
From Python 3.3, the builtin open()
has an x
mode that means "open for exclusive creation, failing if the file already exists".
这篇关于如何在python中创建文件而不覆盖现有文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!