如何用Python复制文件?
发布于 2018-08-16 15:15:59
复制文件是一个相对简单的操作,如下面的示例所示,但是你应该使用shutil stdlib模块
def copyfileobj_example(source, dest, buffer_size=1024*1024):
"""
Copy a file from source to dest. source and dest
must be file-like objects, i.e. any object with a read or
write method, like for example StringIO.
"""
while True:
copy_buffer = source.read(buffer_size)
if not copy_buffer:
break
dest.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)
发布于 2018-08-16 16:05:01
shutil
有很多你可以使用的方法。其中之一是:
from shutil import copyfile
copyfile(src, dst)
将名为src的文件的内容复制到名为dst的文件中。 目的地位置必须是可写的; 否则,将引发IOError异常。 如果dst已经存在,它将被替换。 使用此功能无法复制特殊文件,如字符或块设备和管道。 src和dst是以字符串形式给出的路径名。
https://stackoverflow.com/questions/-100000595
复制相似问题