What does python3 open "x" mode do?
Yes, that's basically it. It calls the underlying operating system code with the two flags O_CREAT
and O_EXCL
, which attempts to open the file exclusively, creating a new one if it doesn't currently exist.
It's handy if you may find two instances of your program running concurrently, the use of x
mode will ensure only one will successfully create a file, with the other one failing.
A classic example is daemons that write their process ID into a pid
file (so that can be easily signalled later on). By using x
, you can guarantee that only one daemon can be running at a time, something that's harder to do without the x
mode, and prone to race conditions.
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
To put simple, opening a file with 'x'
mode means:
Atomically do: (check if exists and create file)