python3打开“x”模式做什么?

2024-04-29 23:18:06 发布

您现在位置:Python中文网/ 问答频道 /正文

新的打开文件模式“x”在python 3中做什么?

这是python 3的文件:

'r': open for reading (default)

'w': open for writing, truncating the file first

'x': open for exclusive creation, failing if the file already exists

'a': open for writing, appending to the end of the file if it exists

'b': binary mode

't': text mode (default)

'+': open a disk file for updating (reading and writing)

'U': universal newlines mode (deprecated)

“独家创作”是什么意思?

我测试了“x”模式并找到了一些:

  • 不能与“r/w/a”一起使用
  • “x”只可写x+“可以读写
  • 文件必须在open之前不存在
  • 文件将在open之后创建

所以“x”与“w”类似。但对于“x”,如果文件存在,则引发FileExistsError。对于“w”,它只需创建一个新文件/截断现有文件。

我说得对吗?这是唯一的区别吗?


Tags: 文件thedefaultforifmodeexists模式
3条回答

正如@Martjin已经说过的,你已经回答了你自己的问题。我只想对手册中的解释加以详细说明,以便更好地理解正文

“x”:打开进行独占创建,如果文件已存在则失败

当您指定exclusive creation时,这显然意味着您将使用此模式以独占方式创建文件。当您不会意外地使用wa模式截断/追加现有文件时,就需要这样做。

如果没有这种情况,开发人员应该谨慎地检查文件的存在性,然后跳转到打开文件进行更新。

使用此模式,您的代码将简单地编写为

try:
    with open("fname", "x") as fout:
        #Work with your open file
except FileExistsError:
    # Your error handling goes here

以前你的代码可能是

import os.path
if os.path.isfile(fname):
    # Your error handling goes here
else:
    with open("fname", "w") as fout:
        # Work with your open file

是的,基本上就是这样。

如果您发现程序的两个实例同时运行,那么使用x模式将确保只有一个将成功创建一个文件,而另一个将失败。

一个典型的例子是将进程ID写入pid文件的守护进程(这样就可以很容易地发出信号)。通过使用x,您可以保证一次只能运行一个守护进程,这在没有x模式和容易出现竞争条件的情况下是很难做到的。

简而言之,使用'x'模式打开文件意味着:

原子do:(检查是否存在并创建文件)

相关问题 更多 >