[Tutor] Using read() before closing a file
Alan Gauld
alan.gauld at btinternet.com
Tue May 5 19:37:42 CEST 2009
"Eduardo Vieira" <eduardo.susan at gmail.com> wrote
>>>> arq = open('c:/myscripts/simple2.ttt', 'w')
>>>> arq.write('The length is %d' % len(a))
>>>> res = arq.read()
>>>> print res
>
> The print doesn't print the text I had written,
That's because of two things:
a) You opened the file for write only not reading
b) You had moved the file cursor beyond the text you wrote
On (b): the file is conceptually a sequential data stream
so think of the cursor in a text editor line. After you have
written something you cannot select what you have
written unless you cursor back to the beginning.
Similarly with a file. Even if you opened it with rw
access you would still need to position the cursor
(with the seek() call) to the point before what you
wrote to be able to read it. After reading it the cursor
would once again be at the end of the file and you
could write more data.
> But if I had closed the file and
> then did this: res = open('c:/myscripts/simple2.ttt').read(), it would
> have worked.
Thats right because you now open the file for reading,
therefore the cursor is repositioned at he start of the file and
the mode is set correctly.
HTH,
--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/
More information about the Tutor
mailing list