What does python3 open “x” mode do?

前端 未结 3 1575
情深已故
情深已故 2021-01-01 09:51

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

3条回答
  •  情歌与酒
    2021-01-01 10:40

    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.

提交回复
热议问题