Python资料之shutil模块

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"""
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值