What makes python3 open x mode?

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

here is a python 3 document:

'r': open for reading (default)

'w': open for recording by trimming the file first

'x': open for exclusive creation if file already exists

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

'b': binary mode

't': text mode (default)

'+': open the disk file for updating (read and write)

'U': generic newlines (obsolete)

What does exclusive creation mean?

I test the "x" mode and detect:

  • It cannot be used with "r / w / a"
  • "x" is written only. "x +" can write and read
  • 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 a FileExistsError . For "w," it will simply create a new file / truncate an existing file.

I'm right? Is that the only difference?

+19
python
source share
3 answers

As @Martjin already said, you already answered your question. I would only reinforce the explanation in the manual to better understand the text.

'x': open for exclusive creation if file already exists

When you specify exclusive creation , this clearly means that you should use this mode to exclusively create the file. The need for this is necessary if you do not accidentally truncate / add an existing file with any of the w or a modes.

In the absence of this, developers should be careful to check for the presence of a file before jumping to open the file for updating.

In this mode, your code will simply be written as

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

Previously, although your code could have 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 
+14
source share

Yes, that’s basically it.

This is convenient if you can simultaneously find two instances of your program, using x mode ensures that only one of them will successfully create the file, and the other will fail.

A classic example is daemons that write their process identifier to a pid file (so that it can be easily signaled). Using x , you can guarantee that only one daemon can work at a time, which is more difficult to do without x mode and is subject to race conditions.

+4
source share

Simply put, opening a file in 'x' mode means:

Atomic to do: (check if exists and create file)

0
source share

All Articles