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':打开独占创建,如果文件已经存在则失败
当你指定独占创建
时,很明显的意思是,你会使用这种模式独占创建文件。当您不会使用 w
或 a
模式意外截断/附加现有文件时,需要这样做。
如果没有此功能,开发人员应谨慎检查文件是否存在,然后再打开文件进行更新。
使用此模式,您的代码将被简单地编写为
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/