python3打开“x"是做什么的?模式吗? [英] What does python3 open "x" mode do?

查看:102
本文介绍了python3打开“x"是做什么的?模式吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

python 3 中新的打开文件模式x"有什么作用?

What does the new open file mode "x" do in python 3?

这里是 python 3 的文档:

'r':打开阅读(默认)

'r': open for reading (default)

'w':打开写入,先截断文件

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

'x':为独占创建打开,如果文件已经存在则失败

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

'a':打开写入,如果存在则追加到文件末尾

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

'b':二进制模式

't':文本模式(默认)

't': text mode (default)

'+':打开磁盘文件进行更新(读写)

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

'U':通用换行模式(已弃用)

'U': universal newlines mode (deprecated)

独家创作"是什么意思?

What does "exclusive creation" mean?

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

I test the "x" mode and find some:

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

因此,x"类似于w".但是对于x",如果文件存在,则引发 FileExistsError.对于w",它只会创建一个新文件/截断现有文件.

So, "x" is similar to "w". But for "x", if the file exists, raise FileExistsError. For "w", it will simply create a new file / truncate the existed file.

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

Am I right? Is this the only difference?

推荐答案

正如@Martjin 所说,您已经回答了自己的问题.我只会放大手册中的解释,以便更好地理解文本

As @Martjin has already said, you have already answered your own question. I would only be amplifying on the explanation in the manual so as to get a better understanding of the text

'x':为独占创建打开,如果文件已经存在则失败

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

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

When you specify exclusive creation, it clearly means, you would use this mode for exclusively creating the file. The need for this is required when you won't accidentally truncate/append an existing file with either of the modes w or a.

如果没有这个,开发者在跳转打开文件进行更新之前应该谨慎地检查文件是否存在.

In absence of this, developers should be cautious to check for the existence of the file before leaping to open the file for updation.

在这种模式下,您的代码将被简单地编写为

With this mode, your code would be simply be written as

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

以前虽然您的代码可能已编写为

Previously though your code might had been written as

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

这篇关于python3打开“x"是做什么的?模式吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆