Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
83 views
in Technique[技术] by (71.8m points)

python - What does python3 open "x" mode do?

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

here is the doc of 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)

What does "exclusive creation" mean?

I test the "x" mode and find some:

  • It can not be used with "r/w/a"
  • "x" is only writeable. "x+" can write and read
  • The file must not exist before open
  • The file will be created after open

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?

question from:https://stackoverflow.com/questions/29295654/what-does-python3-open-x-mode-do

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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': open for exclusive creation, failing if the file already exists

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...