How to copy a binary file?

Robert Wentworth rhww at erols.com
Wed Jan 19 22:56:31 EST 2000


It seems like a simple enough task: I want to copy a
set of JPEG image files, unmodified.  My first attempt 
looked like:

def file_copy(source, dest):
    in_file = open(source, 'r')
    out_file = open(dest, 'w')
    temp = in_file.read()
    out_file.write(temp)
    in_file.close()
    out_file.close()

The library documentation says that "read" without an argument
reads "until EOF", though "for some files like tty's it makes
sense to read beyond EOF."  However, the above function fails
because the initial read() reads only a small number of bytes.
If I try to read() again, there are more bytes to be read.

I suppose I could keep calling read() and writing out the
results until read() returned nothing more.  But this seems
clunky and counterintuitive, and without further testing I'm
not sure this wouldn't leave out some character that needs to
appear between read() results.

What is the preferred way of copying a binary file?

Bob Wentworth

[Please reply to rhww at erols.com]



More information about the Python-list mailing list