如何在python中创建文件而不覆盖现有文件

编程入门 行业动态 更新时间:2024-10-22 20:25:42
本文介绍了如何在python中创建文件而不覆盖现有文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

当前,我有一个循环,试图通过在文件名字符串中添加后缀来查找未使用的文件名.一旦找不到文件,它将使用无法以该名称打开新文件的名称.问题在于此代码在网站中使用,并且可能同时尝试多次执行同一操作,因此存在竞争条件.

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中创建文件而不覆盖现有文件

本文发布于:2023-10-04 09:19:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1467145.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件   而不   如何在   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!