[Tutor] Simultaneous read and write on file
Cameron Simpson
cs at zip.com.au
Mon Jan 18 15:43:18 EST 2016
On 18Jan2016 16:29, ALAN GAULD <alan.gauld at btinternet.com> wrote:
>On 18/01/16 16:01, Anshu Kumar wrote:
>> 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().
Agreed.
>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.
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.
Tip for new players: if you do any .write()s, remember to do a .flush() before
doing a seek or a read - unlike the C stdio library where the flush is
automatic in Python the io classes require you to flush written data if you
read or seek. (You don't have to flush before close, close does that for you.)
>(*)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)
Only on Windows. On UNIX everything is fine unless you go out of your way to
make things harder with locking.
>> 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.
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.
He _may_ be safer opening the file twice - once for "rb" and once for "ab" -
because he does not have to juggle the modes, but it isn't necessarily what he
wants.
Cheers,
Cameron Simpson <cs at zip.com.au>
More information about the Tutor
mailing list