Improvements to copyfile(): open the files in binary mode, and close

them in a finally clause.
This commit is contained in:
Guido van Rossum 1997-04-29 13:08:15 +00:00
parent e9a0732cd1
commit 277206b08e

View file

@ -1,4 +1,5 @@
# Module 'shutil' -- utility functions usable in a shell-like program # Module 'shutil' -- utility functions usable in a shell-like program
# XXX The copy*() functions here don't copy the data fork on Mac
import os import os
@ -8,12 +9,21 @@ MODEBITS = 010000 # Lower 12 mode bits
# Copy data from src to dst # Copy data from src to dst
# #
def copyfile(src, dst): def copyfile(src, dst):
fsrc = open(src, 'r') fsrc = None
fdst = open(dst, 'w') fdst = None
try:
fsrc = open(src, 'rb')
fdst = open(dst, 'wb')
while 1: while 1:
buf = fsrc.read(16*1024) buf = fsrc.read(16*1024)
if not buf: break if not buf:
break
fdst.write(buf) fdst.write(buf)
finally:
if fdst:
fdst.close()
if fsrc:
fsrc.close()
# Copy mode bits from src to dst # Copy mode bits from src to dst
# #