[Tutor] Simultaneous read and write on file
Alan Gauld
alan.gauld at btinternet.com
Mon Jan 18 16:07:49 EST 2016
On 18/01/16 20:43, Cameron Simpson wrote:
>> 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.
>
> But if he wants to mix the modes, he certainly should be experimenting. Having
> a file open for read and write is sometimes useful; I do it myself in certain
> circumstances.
Yes and so have I. Maybe twice in 30 years of programming.
It's sometimes necessary but it's much, much harder to get
right and very easy to get wrong, usually with data corruption
as a result.
So for a beginner I would never encourage it. For an
experienced programmer sure' if there is no other option
(and especially if you have fixed size records where
things get easier).
> Tip for new players: if you do any .write()s, remember to do a .flush() before
> doing a seek or a read
That's exactly my point. There are so many things you have
to do extra when working in mixed mode. Too easy to treat
things like normal mode files and get it wrong. Experts
can do it and make it work, but mostly it's just not needed.
> Disagree. As far as his question goes, "wb+" is a correct mode for what he is
> trying. Whether it is a sensible approach depends very much on what he is doing
> with his files.
I'm not sure we know what he(?) is trying.
We only know he successfully overwrote his data and
that apparently was not his intention. There are use
cases where it makes sense but in most cases you can
get by just fine without.
--
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