Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python file open function modes

Tags:

python

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?

like image 203
NameOfTheRose Avatar asked Jul 19 '15 14:07

NameOfTheRose


People also ask

What 3 modes are used in open statement of text files?

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.

What is a mode in open function in file handling?

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)


1 Answers

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.

like image 157
tmr232 Avatar answered Oct 01 '22 14:10

tmr232