[Tutor] Simultaneous read and write on file

Peter Otten __peter__ at web.de
Mon Jan 18 16:29:02 EST 2016


Anshu Kumar wrote:

> Hello Everyone,
> 
> I try below code in python 2.7.10 to first create and write into a file
> and
> then read and write that file but what i get is just a  file with new
> content.
> 
> 
>>>> with open('test.txt', 'wb+') as f:
> ...     f.write('this is test file.')
> ...     f.write('ok!!!')
> ...
>>>> with open('test.txt', 'wb+') as f:
> ...     a_str = f.read() + 'read the file'
> ...     f.seek(0)
> ...     f.write(a_str)
> ...
> 
> 
> I have read in documentation that wb+ mode is for writing and reading. Am
> i using wrong mode, should i use rb+ ?

Quoting https://docs.python.org/2.7/library/functions.html#open

"""
note that 'w+' truncates the file.
"""

That's why you lose the file's current content, and, yes, "r+b" would avoid 
that.



More information about the Tutor mailing list