shutil
模块是对 os
模块的补充,主要对文件的拷贝、删除、移动、压缩和解压操作
拷贝文件内容到另一个文件
shutil.copyfileobj(fsrc, fdst[, length=16*1024])
源码:
def copyfileobj(fsrc, fdst, length=16*1024):
while 1:
buf = fsrc.read(length)
if not buf:
break
fdst.writer(buf)
使用:
import shutil
s = open('a.txt', 'r')
d = open('b.txt', 'w')
shutil.copyfileobj(s, d)
Tips:
fsrc、fdst
都是文件对象
拷贝整个文件
shutil.copyfile(src, dst)
源码:
def copyfile(src, dst, *, follow_symlinks=True):
if _samefile(src, dst):
raise SameFileError("{!r} and {!r} are the same file".format(src, dst))
for fn in [src, dst]:
try:
st = os.stat(fn)
except OSError:
pass
else:
if stat.S_ISFIFO(st.st_mode):
raise SpecialFileError("`%s` is a named pipe" % fn)
if not follow_symlinks and os.path.islink(src):
os.symlink(os.readlink(src), dst)
else:
with open(src, 'rb') as fsrc:
with open(dst, 'wb') as fdst:
copyfileobj(fsrc, fdst)
return dst