Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

file

I have recently been going through some of our windows python 2.4 code and come across this:

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

I know what w, u and a do on their own, but what happens when you combine them?

like image 289
Harley Holcombe Avatar asked Dec 30 '22 23:12

Harley Holcombe


2 Answers

The a is superfluous. wua is the same as wu since w comes first and will thus truncate the file. If you would reverse the order, that is, auw, that would be the same as au. Visualized:

>>> 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 former appends while the other truncates.)

like image 101
Stephan202 Avatar answered Jan 04 '23 17:01

Stephan202


I did not notice that you knew what the modifiers did. Combined they will do the following:

A and W together is superfluous since both will open for writing. When using W, the file will be overwritten. When using A, all new text is appended after the existing content.

U means "open file XXX for input as a text file with universal newline interpretation".

  • W is for Write
  • A is for Append
  • U will convert the file to use the defined newline character.

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

like image 44
alexn Avatar answered Jan 04 '23 15:01

alexn