What is the "wua" mode when opening a file in python?

I recently looked through some of our python 2.4 windows codes and came across this:

self.logfile = open(self.logfile_name, "wua") 

I know that w , u and a do it all by themselves, but what happens when you combine them?

+4
source share
3 answers

a is redundant. wua matches wu since w comes first and thus truncates the file. If you change the order, i.e. auw , it will be the same as au . Visualization:

 >>> f = open('test.txt', 'r') >>> f.read() 'Initial contents\n' >>> f.close() >>> f = open('test.txt', 'wua') >>> print >> f, 'writing' >>> f.close() >>> f = open('test.txt', 'r') >>> f.read() 'writing\n' >>> f.close() >>> f = open('test.txt', 'auw') >>> print >> f, 'appending' >>> f.close() >>> f = open('test.txt', 'r') >>> f.read() 'writing\nappending\n' >>> f.close() 

(Reminder: both a and w open the file for writing , but the first one adds and the other truncates.)

+5
source

I didnโ€™t notice that you knew you did the modifiers. In combination, they will do the following:

A and W together are redundant, as both will be open for recording. When using W, the file will be overwritten. When using A, all new text is added after existing content.

U means "open file XXX for input as a text file with a universal interpretation of a new line."

  • W for recording
  • A to add
  • U will convert the file to use certain newlines.

More details here: http://codesnippets.joyent.com/posts/show/1969

+3
source

Under the hood, Python 2.4 passes inline open arguments to the fopen operating system. Python does some manipulation of the mode string under certain conditions.

 if (strcmp(mode, "U") == 0 || strcmp(mode, "rU") == 0) mode = "rb"; 

So, if you pass uppercase U or rU , it will open the file for binary reading. If you look at the source of GNU libc and according to the MSDN page describing the implementation of Windows fopen , the parameter โ€œ26โ€ is ignored.

More than one mode pointer (' r ', ' w ' and ' a ') does not work in the mode line. This can be seen by looking at the GNU libc string parsing implementation:

 switch (*mode) { case 'r': omode = O_RDONLY; break; case 'w': omode = O_WRONLY; oflags = O_CREAT|O_TRUNC; break; case 'a': omode = O_WRONLY; oflags = O_CREAT|O_APPEND; break; default: __set_errno (EINVAL); return NULL; } 

The first character of the mode line searches for one of " r ", " w " or " a ", if it is not one of these characters, an error occurs.

Therefore, when a file is opened as " wua ", it will be open only for writing, created if it does not exist and is not truncated. ' U ' and ' a ' will be ignored.

+2
source

All Articles