2

Is there a documented ordering to the characters in an open file's .mode in python?

I'm interested in safely determining the mode of a file-like object I'm receiving as a parameter. Is there a documented list of all possible modes of an open file? I could create an exhaustive list of all permutations of the flags that open(, mode=...) takes, but some will be nonsensical (ax).

I'm more interested in the possible values of the mode attribute of a file like object - and especially the order that I can expect those flags to appear. For instance here's 4 different ways to open a file that all create a file-like object in rb+ mode.

In [1]: with open('/tmp/foo', 'r+b') as foo:
   ...:     print(foo.mode)
   ...: 
rb+

In [2]: with open('/tmp/foo', 'rb+') as foo:
   ...:     print(foo.mode)
   ...: 
rb+

In [3]: with open('/tmp/foo', 'br+') as foo:
   ...:     print(foo.mode)
   ...: 
rb+

In [4]: with open('/tmp/foo', 'bw+') as foo:
   ...:     print(foo.mode)
   ...: 
rb+

Essentially my question is if there is any documented determinism to the order of the file-mode characters (incl. across platforms)? It's clearly not just sorted in alphanumeric order.

This question (Confused by python file mode "w+") is the closest answer I could find, but there's no references, and no explanation of how I can trust that python will never return any of the equivalent modes above when calling <file>.mode (br+, r+b, w+b, wb+ for what is reported as rb+ on my system).

Zev Isert
  • 915
  • 11
  • 20
  • Chances that it's inspired by the C file-opening mode. Just type in `man fopen` in a Unix/Linux shell and you'll see the difference between `r+` and `w+` according to the C language. Nothing sure but the behavior could be the same. Maybe nothing more in my comment than [Confused by python file mode "w+"](https://stackoverflow.com/questions/16208206/confused-by-python-file-mode-w). But needs to be said. – 0x0fba Nov 14 '22 at 23:25

0 Answers0