python--shutil模块

 

查看shutil模块源码方法:

>>>import shutil
>>>shutil.__file__

输出shutil模块源码所在路径,下的shutil.py即为shutil源码文件

1、shutil.copyfileobj(fsrc,fdst[,length=16*1024]) 

copy文件内容到另一个文件,可以copy指定大小的内容,默认未16*1024

源码:

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)

实例:

import shutil


fsrc= open(src_path,'r')
fdst= open(dst_path,'w+')
shutil.copyfileobj(fsrc,fdst) 

2、shutil.copyfile(src,dst)

copy文件内容,不需要用open函数打开文件

源码:

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)

实例:

import shutil

shutil.copyfile('src','dst')

3、shutil.copymode(src,dst)

仅copy权限,不更改文件内容、组和用户

源码:

def copymode(src, dst):
    """Copy mode bits from src to dst"""
    if hasattr(os, 'chmod'):
        st = os.stat(src)
        mode = stat.S_IMODE(st.st_mode)
        os.chmod(dst, mode)

实例:

#先看两个文件的权限
[root@slyoyo python_test]# ls -l
total 4
-rw-r--r--. 1 root root 79 May 14 05:17 test1
-rwxr-xr-x. 1 root root  0 May 14 19:10 test2

#运行命令
>>> import shutil
>>> shutil.copymode('test1','test2')

#查看结果
[root@slyoyo python_test]# ls -l
total 4
-rw-r--r--. 1 root root 79 May 14 05:17 test1
-rw-r--r--. 1 root root  0 May 14 19:10 test2

#当我们将目标文件换为一个不存在的文件时报错
>>> shutil.copymode('test1','test3')    
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/python/lib/python3.4/shutil.py", line 132, in copymode
    chmod_func(dst, stat.S_IMODE(st.st_mode))
FileNotFoundError: [Errno 2] No such file or directory: 'test233'
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值