Python file open function modes

The D flag seems to be Windows specific. Windows seems to add several flags to the fopen function in its CRT, as described here.

While Python does filter the mode string to make sure no errors arise from it, it does allow some of the special flags, as can be seen in the Python sources here. Specifically, it seems that the N flag is filtered out, while the T and D flags are allowed:

while (*++mode) {
    if (*mode == ' ' || *mode == 'N') /* ignore spaces and N */
        continue;
    s = "+TD"; /* each of this can appear only once */
    ...

I would suggest sticking to the documented options to keep the code cross-platform.


This is a bit misleading. open() as mode arg accepts any character, while you pass a valid one i.e.: "w,r,b,+,a".

Thus you can write: open("fname", "w+ANYTHINGYOUWANT"). It will open file as open("fname", "w+"). And open("fname", "rANYTHINGYOUWANT"). will open file as open("fname", "r").

Regarding "U" flag:

In addition to the standard fopen() values mode may be 'U' or 'rU'. Python is usually built with universal newlines support; supplying 'U' opens the file as a text file, but lines may be terminated by any of the following: the Unix end-of-line convention '\n', the Macintosh convention '\r', or the Windows convention '\r\n'. All of these external representations are seen as '\n' by the Python program. If Python is built without universal newlines support a mode with 'U' is the same as normal text mode. Note that file objects so opened also have an attribute called newlines which has a value of None (if no newlines have yet been seen), '\n', '\r', '\r\n', or a tuple containing all the newline types seen.

As you can read in Python documentation https://docs.python.org/2/library/functions.html#open

EDIT:

D: Specifies a file as temporary. It is deleted when the last file pointer is closed.

as you can read in @tmr232's link.

The c, n, t, S, R, T, and D mode options are Microsoft extensions for fopen and _fdopen and should not be used where ANSI portability is desired

Further update:

I propose to submit the phenomenon as a bug, because opening a file as read only i.e. with flag "r", then allowing to delete after/via closing it adding a single character like "D", even accidentally is a serious security issue, I think.

But, if this has some unavoidable functionality, please inform me.

Tags:

Python