Reading, writing files
marduk at letterboxes.org
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
> def copyFile(oldFile, newFile):
> f1 = open(oldFile, 'r')
> f2 = open(newFile, 'w')
> while True:
> text = f1.read(50)
> if text == "":
> My question is why does this function successfully copy a 200
> character file, oldFile, to newFile? The line of code that reads, text
> = f1.read(50), 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 f1.read(50) returns "", which causes the loop to
> Again, much thanks to anyone who can clear this up.
More information about the Python-list