[Tutor] Simultaneous read and write on file

Alan Gauld alan.gauld at btinternet.com
Mon Jan 18 11:29:44 EST 2016


On 18/01/16 16:01, 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)
> ...

You called f.seek(0) which puts the cursor right back to the start
of the file. Try writing without using the f.seek().

But since you only want to append, it would be better and safer to use
append mode instead.

The + modes are deceptively appealing but they are full of dangers
for precisely the reasons you have discovered(*). You very rarely
need them and you are better opening/closing the file and
using explicit modes to read/write.

(*)Another problem, apart from the risks of overwriting your
data,  is that the + modes will lock the file even while you
are just reading it, which might cause a problem with shared
files)

> I have read in documentation that wb+ mode is for writing and reading. Am i
> using wrong mode, should i use rb+ ?

No, you should probably be separately using 'r' to read and 'a'
to append.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list