Confused by Python File Mode "W+"

Confused by python file mode w+

Let's say you're opening the file with a with statement like you should be. Then you'd do something like this to read from your file:

with open('somefile.txt', 'w+') as f:
# Note that f has now been truncated to 0 bytes, so you'll only
# be able to read data that you write after this point
f.write('somedata\n')
f.seek(0) # Important: return to the top of the file before reading, otherwise you'll just read an empty string
data = f.read() # Returns 'somedata\n'

Note the f.seek(0) -- if you forget this, the f.read() call will try to read from the end of the file, and will return an empty string.

Difference between modes a, a+, w, w+, and r+ in built-in open function?

The opening modes are exactly the same as those for the C standard library function fopen().

The BSD fopen manpage defines them as follows:

 The argument mode points to a string beginning with one of the following
sequences (Additional characters may follow these sequences.):

``r'' Open text file for reading. The stream is positioned at the
beginning of the file.

``r+'' Open for reading and writing. The stream is positioned at the
beginning of the file.

``w'' Truncate file to zero length or create text file for writing.
The stream is positioned at the beginning of the file.

``w+'' Open for reading and writing. The file is created if it does not
exist, otherwise it is truncated. The stream is positioned at
the beginning of the file.

``a'' Open for writing. The file is created if it does not exist. The
stream is positioned at the end of the file. Subsequent writes
to the file will always end up at the then current end of file,
irrespective of any intervening fseek(3) or similar.

``a+'' Open for reading and writing. The file is created if it does not
exist. The stream is positioned at the end of the file. Subse-
quent writes to the file will always end up at the then current
end of file, irrespective of any intervening fseek(3) or similar.

I'm trying to understand binary file mode in Python

In text mode what matters is... text. There are "normal" characters (letters, numbers, punctuation and so on) and there are special characters. Many of the latter, for example the new line char (\n), the carriage return (\r) and the tabulation (\t) have a specific role in affecting the presentation of the text.

That's why in text mode \r\n is shown as a new line, and not explicitly.

In binary mode is different: all characters are supposed to be just bytes, not something to be interpreted to better present a text. And that's why all the characters are shown when it comes to print the content of a file open in binary mode.

Note: the b shown at the beginning, just before the actual file, just means "here it is a file presented in binary mode".

Confusion about different file modes

r+ starts at beginning of file, but will not create a new file if it doesn't exists.

w+ truncates existing file to zero length if the file exists, otherwise creates a new file.

a+ starts at end of file if file exists, otherwise creates a new file.

Access modes r+, w+ and a+ opens the file in read and write mode, but with the above difference:

Both r+ and w+ we can read ,write on file but r+ does not truncate (delete) the content of file as well it doesn’t create a new file if such file doesn’t exits while in w+ truncate the content of file as well as create a new file if such file doesn’t exists.

File mode for creating+reading+appending+binary

The mode is ab+ the r is implied and 'a'ppend and ('w'rite '+' 'r'ead) are redundant. Since the CPython (i.e. regular python) file is based on the C stdio FILE type, here are the relevant lines from the fopen(3) man page:

  • w+ Open for reading and writing.
    The file is created if it does not
    exist, otherwise it is truncated.
    The stream is positioned at the
    beginning of the file.

  • a+ Open for reading and appending (writing at end of file).
    The file is created if it does not
    exist. The initial file position
    for reading is at the beginning of
    the file, but output is always
    appended to the end of the file.

With the "b" tacked on to make DOS happy. Presumably you want to do something like this:

>>> f = open('junk', 'ab+')
>>> f
<open file 'junk', mode 'ab+' at 0xb77e6288>
>>> f.write('hello\n')
>>> f.seek(0, os.SEEK_SET)
>>> f.readline()
'hello\n'
>>> f.write('there\n')
>>> f.seek(0, os.SEEK_SET)
>>> f.readline()
'hello\n'
>>> f.readline()
'there\n'

unpickling in w+b mode in python

Opening a file in w+b will truncate the file. If you want to open a file for reading and writing without truncation, you should use r+b.

File not overwritten though opened in 'w' mode in python?

You should maybe switch the order of your loops. It is true as you say that 'w' mode erases the content of the file, but it does it when you call the open function instead of when you call write.

from threading import *

def function():
while True:
with open('important.cache', 'w') as f:
f.write(str(last_index))

mythread = Thread(target=function)
mythread.start()

You'll see that sometimes the important.cache file will be empty. This is because the while loop is very very fast and it is erasing and writing the file very fast. For solving that, you should maybe call a small sleep after the write statement (time.sleep(0.01)) would probably work.



Related Topics



Leave a reply



Submit