[Tutor] File mode r+

Shitiz Bansal shitizb at yahoo.com
Wed Sep 28 02:14:37 CEST 2005



--- "Michael P. Reilly" <arcege at gmail.com> wrote:

> On 9/24/05, Shitiz Bansal <shitizb at yahoo.com> wrote:
> >
> > Hi,
> >
> > How do i proceed if i am not sure about the number
> of characters in the
> > fist two lines and want to write in the third
> line.is <http://line.is>there a way to skip two
> lines and write on the third??
> >
> > Also could anyone explain why the readline() did
> not work. according to
> > what i understand it should.
> > *bob <bgailer at alum.rpi.edu>* wrote:
> >
> > At 01:11 AM 9/24/2005, Shitiz Bansal wrote:
> > >Hi,
> > >I want to update a textfile using the r+ file
> mode.
> > >contents of file:
> > >
> > >abcd
> > >efgh
> > >ijkl
> > >mnop
> > >qrst
> > >uvwx
> > >yx12
> > >
> > >my scripts is:
> > >
> > >file1=open("aa.txt",'r+')
> >
> > >>Instead of readline, use skip to position the
> file to where you want to
> > >>overwrite it.
> > >>file1.seek(10)
> >
> >
> > >file1.readline()
> > >file1.readline()
> > >file1.write("1234\n")
> > >file1.close()
> > >
> > >This should replace the third line with 1234.
> > >However it does nothing.
> > >
> > >Moreover the script:
> > >
> > >file1=open("aa.txt",'r+')
> > >file1.write("1234\n")
> > >file1.close()
> > >
> > >does replace the first line with 1234.
> > >
> > >could anyone explain what is happening?
> > >
> > >shitiz
> >
> > Hello Shitiz,
> 
> I'm not sure if it is true anymore, I haven't gotten
> to test it. But in the
> olden days of C and standard libraries and UNIX, you
> would open a file for
> reading and writing and before you could switch
> between read() and write()
> you would have to perform a seek(). Usually
> something like:
> file.readline() # read line 1
> file.readline() # read line 2
> file.seek(0, 1) # move 0 bytes from current position
> (no place)
> file.write("1234\n")
> file.close()
>  There may be one problem here. What you write will
> overwrite line 3.... or
> only part of line 3... or maybe all of line 3 and
> some of line 4. It is good
> to know how the file is structured before you write
> to it, in case you end
> up with unexpected data. If all your lines are four
> characters plus a
> newline, then you don't have to worry (most of us
> aren't that lucky).
> -Arcege
> --
> There's so many different worlds,
> So many different suns.
> And we have just one world,
> But we live in different ones.
> 



		
__________________________________ 
Yahoo! Mail - PC Magazine Editors' Choice 2005 
http://mail.yahoo.com


More information about the Tutor mailing list