I have noticed that, in addition to the documented mode characters, Python 2.7.5.1 in Windows XP and 8.1 also accepts modes U
and D
at least when reading files. Mode U
is used in numpy's genfromtxt
. Mode D
has the effect that the file is deleted, as per the following code fragment:
f = open('text.txt','rD')
print(f.next())
f.close() # file text.txt is deleted when closed
Does anybody know more about these modes, especially whether they are a permanent feature of the language applicable also on Linux systems?
Opening a file r - open a file in read mode. w - opens or create a text file in write mode. a - opens a file in append mode.
Working of open() function Before performing any operation on the file like reading or writing, first, we have to open that file. For this, we should use Python's inbuilt function open() but at the time of opening, we have to specify the mode, which represents the purpose of the opening file. f = open(filename, mode)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With