Reading, writing files

Albert Hopkins marduk at
Sat Aug 22 00:42:56 CEST 2009

On Fri, 2009-08-21 at 15:21 -0700, seanm wrote:
> In the book I am using, they give the following function as an
> example:
> def copyFile(oldFile, newFile):
>     f1 = open(oldFile, 'r')
>     f2 = open(newFile, 'w')
>     while True:
>         text =
>         if text == "":
>             break
>         f2.write(text)
>     f1.close()
>     f2.close()
>     return
> My question is why does this function successfully copy a 200
> character file, oldFile, to newFile? The line of code that reads, text
> =, does not seem to be iterative in any way to me. How is
> this fuction succeding in adding each additional set up 50 characters
> to the previous set of 50 characters read from oldFile?

The body of the loop will execute forever (unless cut short by the
"break" statement.  What the loop is essentially doing is reading 50
bytes at a time from f1 and writing it into f2.  When f1 reaches end of
file it will stop returning bytes (if text == "":) the loop is broken
and both files are closed.

> How does it even succeed in copying a 25 character file? If oldFile
> contains 25 characters, how does the program ever break out of the
> 'while True:' loop?
> I just don't see it.

Have you read the documentation for file objects?

During the first iteration of the loop 25 bytes are read from f1. Then
they are written to f2.  During the next iteration there is nothing else
to be read from f1 so returns "", which causes the loop to

> Again, much thanks to anyone who can clear this up.

More information about the Python-list mailing list