shutil模块总结

shutil -一种高层次的文件操作工具,强大之处是在对文件的复制与删除操作支持比较好。

shutil.copyfileobj(fsrc, fdst[, length=16*1024])    #copy文件内容到另一个文件,可以copy指定大小的内容

defcopyfileobj(fsrc, fdst, length=16*1024):"""copy data from file-like object fsrc to file-like object fdst"""while1:

buf=fsrc.read(length)ifnotbuf:breakfdst.write(buf)#注意! 在其中fsrc,fdst都是文件对象,都需要打开后才能进行复制操作importshutil

f1=open('name','r')

f2=open('name_copy','w+')

shutil.copyfileobj(f1,f2,length=16*1024)

shutil.copyfile(src,dst)  #copy文件内容,是不是感觉上面的文件复制很麻烦?还需要自己手动用open函数打开文件,在这里就不需要了,事实上,copyfile调用了copyfileobj

实例:

defcopyfile(src, dst, *, follow_symlinks=True):"""Copy data from src to dst.

If follow_symlinks is not set and src is a symbolic link, a new

symlink will be created instead of copying the file it points to."""if_samefile(src, dst):raiseSameFileError("{!r} and {!r} are the same file".format(src, dst))forfnin[src, dst]:try:

st=os.stat(fn)exceptOSError:#File most likely does not existpasselse:#XXX What about other special files? (sockets, devices...)ifstat.S_ISFIFO(st.st_mode):raiseSpecialFileError("`%s` is a named pipe"%fn)ifnotfollow_symlinksandos.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)returndst

删除目录使用如下函数:

shutil.rmtree('d:/dd')

移动文件或者文件夹到另外一个地方:

shutil.move('d:/c.png','e:/')

shutil.copystat(src,dst)    #复制所有的状态信息,包括权限,组,用户,时间等

defcopystat(src, dst, *, follow_symlinks=True):"""Copy all stat info (mode bits, atime, mtime, flags) from src to dst.

If the optional flag `follow_symlinks` is not set, symlinks aren't followed if and

only if both `src` and `dst` are symlinks."""def_nop(*args, ns=None, follow_symlinks=None):pass#follow symlinks (aka don't not follow symlinks)follow = follow_symlinksornot(os.path.islink(src)andos.path.islink(dst))iffollow:#use the real function if it existsdeflookup(name):returngetattr(os, name, _nop)else:#use the real function only if it exists#*and* it supports follow_symlinksdeflookup(name):

fn=getattr(os, name, _nop)iffninos.supports_follow_symlinks:returnfnreturn_nop

st= lookup("stat")(src, follow_symlinks=follow)

mode=stat.S_IMODE(st.st_mode)

lookup("utime")(dst, ns=(st.st_atime_ns, st.st_mtime_ns),

follow_symlinks=follow)try:

lookup("chmod")(dst, mode, follow_symlinks=follow)exceptNotImplementedError:#if we got a NotImplementedError, it's because#* follow_symlinks=False,#* lchown() is unavailable, and#* either#* fchownat() is unavailable or#* fchownat() doesn't implement AT_SYMLINK_NOFOLLOW.#(it returned ENOSUP.)#therefore we're out of options--we simply cannot chown the#symlink.  give up, suppress the error.#(which is what shutil always did in this circumstance.)passifhasattr(st,'st_flags'):try:

lookup("chflags")(dst, st.st_flags, follow_symlinks=follow)exceptOSError as why:forerrin'EOPNOTSUPP','ENOTSUP':ifhasattr(errno, err)andwhy.errno ==getattr(errno, err):breakelse:raise_copyxattr(src, dst, follow_symlinks=follow)

shutil.copy(src,dst)  #复制文件的内容以及权限,先copyfile后copymode


shutil.copytree(src, dst, symlinks=False, ignore=None, copy_function=copy2,ignore_dangling_symlinks=False)  #递归的复制文件内容及状态信息

shutil.rmtree(path, ignore_errors=False, onerror=None)#递归地删除文件

shutil.move(src, dst)    #递归的移动文件

make_archive(base_name, format, root_dir=None, base_dir=None, verbose=0,dry_run=0, owner=None, group=None, logger=None)  #压缩打包

base_name:    压缩打包后的文件名或者路径名

format:          压缩或者打包格式"zip", "tar", "bztar"or "gztar"

root_dir :         将哪个目录或者文件打包(也就是源文件)

实例:

>>> shutil.make_archive('tarball','gztar',root_dir='copytree_test')

[root@slyoyo python_test]#ls -ltotal 12drwxr-xr-x. 3 root  root  4096 May 14 19:36copytree_copy

drwxr-xr-x. 3 root  root  4096 May 14 19:36copytree_test-rw-r--r--. 1 root  root      0 May 14 21:12tarball.tar.gz-rw-r--r--. 1 python python  79 May 14 05:17test1-rw-r--r--. 1 root  root      0 May 14 19:10 test2

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容