python - python3 open "x"模式有什么作用?

标签 python python-3.x

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

这里是 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
  • 之后创建

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

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

最佳答案

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

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

当你指定独占创建时,很明显的意思是,你会使用这种模式独占创建文件。当您不会使用 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

关于python - python3 open "x"模式有什么作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29295654/

相关文章:

python - 从 BigQuery 查询到 Jupyter 时出现 "' NotebookFormatter ' object has no attribute ' get_result '"错误?

python - pandas 映射到数组字典

python - 通过计算乘积来总结 pandas DataFrame

python-3.x - 在 FLASK 中运行 pypupeteer 给出 ValueError : signal only works in main thread

python - 想要使用 python 中的机器学习来增加质心点。?

python - 是否有任何 pythonic 方法将 mysql TO_DAYS 输出转换为日期时间?

python - 在 matplotlib 图中正确显示 x 轴标签

python - 资源未在 Simpy 中发布 - 我做错了什么?

python - 集中跟踪多用户Python应用程序中的用户登录

javascript - 如何通过 Javascript 在 PythonAnywhere 上的 OpenCV 中访问网络摄像头?