shutil模块是高级的文件、文件夹和压缩包的处理模块。
主要方法:
1、shutil.copyfileobj(fsrc, fdst[, length])
Inferred type: (fsrc: {read}, fdst: {write}, length: int)
将文件内容拷贝到另一个文件中,length为每次读取的字节数。
方法定义:
def copyfileobj(fsrc, fdst, length=16*1024):
"""copy data from file-like object fsrc to file-like object fdst"""
while 1:
buf = fsrc.read(length)
if not buf:
break
fdst.write(buf)
使用示例:
#-*- coding:utf-8 -*-
import shutil
f1=open("1.txt","rb")
f2=open("2.txt","wb")
shutil.copyfileobj(f1,f2,5)
2、shutil.copyfile(src, dst)
Inferred type: (src: Union[str, unicode], dst: Union[str, unicode])
拷贝文件(包括文件权限)
方法定义:
def copyfile(src, dst):
"""Copy data from src to dst"""
if _samefile(src, dst):
raise 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 exist
pass
else:
# XXX What about other special files? (sockets, devices...)
if stat.S_ISFIFO(st.st_mode):
raise SpecialFileError("`%s` is a named pipe" % fn)
with open(src, 'rb') as fsrc:
with open(dst, 'wb') as fdst:
copyfileobj(fsrc, fdst)
使用示例:
#-*- coding:utf-8 -*-
import shutil
shutil.copy("1.txt","2.txt")
3、shutil.copymode(src, dst):
Inferred type: (src: Union[str, unicode], dst: Union[str, unicode]) -> None
仅拷贝权限。内容、组、用户均不变
方法定义:
def copymode(src, dst):
"""Copy mode bits from src to dst"""