def copyfileobj_example(source, dest, buffer_size=1024*1024):"""Copy a file from source to dest. source and destmust be file-like objects, i.e. any object with a read orwrite method, like for example StringIO."""while True:copy_buffer = source.read(buffer_size)if not copy_buffer:breakdest.write(copy_buffer)
如果你想按文件名复制,你可以这样做:
def copyfile_example(source, dest):# Beware, this example does not handle any edge cases!with open(source, 'rb') as src, open(dest, 'wb') as dst:copyfileobj_example(src, dst)
with open('sourcefile', 'rb') as f, open('destfile', 'wb') as g:while True:block = f.read(16*1024*1024) # work by blocks of 16 MBif not block: # end of filebreakg.write(block)
from os import path, makedirsfrom shutil import copyfilemakedirs(path.dirname(path.abspath(destination_path)), exist_ok=True)copyfile(source_path, destination_path)
正如已接受的答案所指出的那样,这些行将覆盖目标路径上存在的任何文件,因此有时在该代码块之前添加:if not path.exists(destination_path):可能会很有用。
def copyFile(src, dst, buffer_size=10485760, perserveFileDate=True):'''@param src: Source File@param dst: Destination File (not file path)@param buffer_size: Buffer size to use during copy@param perserveFileDate: Preserve the original file date'''# Check to make sure destination directory exists. If it doesn't create the directorydstParent, dstFileName = os.path.split(dst)if(not(os.path.exists(dstParent))):os.makedirs(dstParent)
# Optimize the buffer for small filesbuffer_size = min(buffer_size,os.path.getsize(src))if(buffer_size == 0):buffer_size = 1024
if shutil._samefile(src, dst):raise shutil.Error("`%s` and `%s` are the same file" % (src, dst))for fn in [src, dst]:try:st = os.stat(fn)except OSError:# File most likely does not existpasselse:# XXX What about other special files? (sockets, devices...)if shutil.stat.S_ISFIFO(st.st_mode):raise shutil.SpecialFileError("`%s` is a named pipe" % fn)with open(src, 'rb') as fsrc:with open(dst, 'wb') as fdst:shutil.copyfileobj(fsrc, fdst, buffer_size)
if(perserveFileDate):shutil.copystat(src, dst)