查看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'