shutil

  -- --High-level file operations  高级的文件操作模块。

  os模块提供了对目录或者文件的新建/删除/查看文件属性,还提供了对文件以及目录的路径操作。比如说:绝对路径,父目录……  但是,os文件的操作还应该包含移动 复制  打包 压缩 解压等操作,这些os模块都没有提供。

  而本章所讲的shutil则就是对os中文件操作的补充。--移动 复制  打包 压缩 解压,

shutil功能:

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

#先来看看其源代码。
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:breakfdst.write(buf)#注意! 在其中fsrc,fdst都是文件对象,都需要打开后才能进行复制操作
import shutil
f1=open('name','r')
f2=open('name_copy','w+')
shutil.copyfileobj(f1,f2,length=16*1024)

View Code

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

def copyfile(src, dst, *, follow_symlinks=True):"""Copy data from src to dst.If follow_symlinks is not set and src is a symbolic link, a newsymlink will be created instead of copying the file it points to."""if _samefile(src, dst):raise SameFileError("{!r} and {!r} are the same file".format(src, dst))for fn in [src, dst]:try:st = os.stat(fn)except OSError:# File most likely does not existpasselse:# XXX What about other special files? (sockets, devices...)if stat.S_ISFIFO(st.st_mode):raise SpecialFileError("`%s` is a named pipe" % fn)if not follow_symlinks and os.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)return dst

查看源代码

shutil.copyfile('name','name_copy_2')
#一句就可以实现复制文件内容

实例

3  shutil.copymode(src,dst)   #仅copy权限,不更改文件内容,组和用户。

def copymode(src, dst, *, follow_symlinks=True):"""Copy mode bits from src to dst.If follow_symlinks is not set, symlinks aren't followed if and onlyif both `src` and `dst` are symlinks.  If `lchmod` isn't available(e.g. Linux) this method does nothing."""if not follow_symlinks and os.path.islink(src) and os.path.islink(dst):if hasattr(os, 'lchmod'):stat_func, chmod_func = os.lstat, os.lchmodelse:returnelif hasattr(os, 'chmod'):stat_func, chmod_func = os.stat, os.chmodelse:returnst = stat_func(src)chmod_func(dst, stat.S_IMODE(st.st_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 copymodechmod_func(dst, stat.S_IMODE(st.st_mode))
FileNotFoundError: [Errno 2] No such file or directory: 'test233'

实例

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

def copystat(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 andonly 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_symlinks or not (os.path.islink(src) and os.path.islink(dst))if follow:# use the real function if it existsdef lookup(name):return getattr(os, name, _nop)else:# use the real function only if it exists# *and* it supports follow_symlinksdef lookup(name):fn = getattr(os, name, _nop)if fn in os.supports_follow_symlinks:return fnreturn _nopst = 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)except NotImplementedError:# 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.)passif hasattr(st, 'st_flags'):try:lookup("chflags")(dst, st.st_flags, follow_symlinks=follow)except OSError as why:for err in 'EOPNOTSUPP', 'ENOTSUP':if hasattr(errno, err) and why.errno == getattr(errno, err):breakelse:raise_copyxattr(src, dst, follow_symlinks=follow)

查看源代码

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

def copy(src, dst, *, follow_symlinks=True):"""Copy data and mode bits ("cp src dst"). Return the file's destination.The destination may be a directory.If follow_symlinks is false, symlinks won't be followed. Thisresembles GNU's "cp -P src dst".If source and destination are the same file, a SameFileError will beraised."""if os.path.isdir(dst):dst = os.path.join(dst, os.path.basename(src))copyfile(src, dst, follow_symlinks=follow_symlinks)copymode(src, dst, follow_symlinks=follow_symlinks)return dst

查看源代码

6  shutil.copy2(src,dst)    #复制文件的内容以及文件的所有状态信息。先copyfile后copystat

def copy2(src, dst, *, follow_symlinks=True):"""Copy data and all stat info ("cp -p src dst"). Return the file'sdestination."The destination may be a directory.If follow_symlinks is false, symlinks won't be followed. Thisresembles GNU's "cp -P src dst"."""if os.path.isdir(dst):dst = os.path.join(dst, os.path.basename(src))copyfile(src, dst, follow_symlinks=follow_symlinks)copystat(src, dst, follow_symlinks=follow_symlinks)return dst

查看源代码

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

def copytree(src, dst, symlinks=False, ignore=None, copy_function=copy2,ignore_dangling_symlinks=False):"""Recursively copy a directory tree.The destination directory must not already exist.If exception(s) occur, an Error is raised with a list of reasons.If the optional symlinks flag is true, symbolic links in thesource tree result in symbolic links in the destination tree; ifit is false, the contents of the files pointed to by symboliclinks are copied. If the file pointed by the symlink doesn'texist, an exception will be added in the list of errors raised inan Error exception at the end of the copy process.You can set the optional ignore_dangling_symlinks flag to true if youwant to silence this exception. Notice that this has no effect onplatforms that don't support os.symlink.The optional ignore argument is a callable. If given, itis called with the `src` parameter, which is the directorybeing visited by copytree(), and `names` which is the list of`src` contents, as returned by os.listdir():callable(src, names) -> ignored_namesSince copytree() is called recursively, the callable will becalled once for each directory that is copied. It returns alist of names relative to the `src` directory that shouldnot be copied.The optional copy_function argument is a callable that will be usedto copy each file. It will be called with the source path and thedestination path as arguments. By default, copy2() is used, but anyfunction that supports the same signature (like copy()) can be used."""names = os.listdir(src)if ignore is not None:ignored_names = ignore(src, names)else:ignored_names = set()os.makedirs(dst)errors = []for name in names:if name in ignored_names:continuesrcname = os.path.join(src, name)dstname = os.path.join(dst, name)try:if os.path.islink(srcname):linkto = os.readlink(srcname)if symlinks:# We can't just leave it to `copy_function` because legacy# code with a custom `copy_function` may rely on copytree# doing the right thing.
                    os.symlink(linkto, dstname)copystat(srcname, dstname, follow_symlinks=not symlinks)else:# ignore dangling symlink if the flag is onif not os.path.exists(linkto) and ignore_dangling_symlinks:continue# otherwise let the copy occurs. copy2 will raise an errorif os.path.isdir(srcname):copytree(srcname, dstname, symlinks, ignore,copy_function)else:copy_function(srcname, dstname)elif os.path.isdir(srcname):copytree(srcname, dstname, symlinks, ignore, copy_function)else:# Will raise a SpecialFileError for unsupported file types
                copy_function(srcname, dstname)# catch the Error from the recursive copytree so that we can# continue with other filesexcept Error as err:errors.extend(err.args[0])except OSError as why:errors.append((srcname, dstname, str(why)))try:copystat(src, dst)except OSError as why:# Copying file access times may fail on Windowsif getattr(why, 'winerror', None) is None:errors.append((src, dst, str(why)))if errors:raise Error(errors)return dst# version vulnerable to race conditions

查看源代码

[root@slyoyo python_test]# tree copytree_test/
copytree_test/
└── test├── test1├── test2└── hahaha[root@slyoyo test]# ls -l
total 0
-rw-r--r--. 1 python python 0 May 14 19:36 hahaha
-rw-r--r--. 1 python python 0 May 14 19:36 test1
-rw-r--r--. 1 root   root   0 May 14 19:36 test2>>> shutil.copytree('copytree_test','copytree_copy')
'copytree_copy'[root@slyoyo python_test]# ls -l
total 12
drwxr-xr-x. 3 root   root   4096 May 14 19:36 copytree_copy
drwxr-xr-x. 3 root   root   4096 May 14 19:36 copytree_test
-rw-r--r--. 1 python python   79 May 14 05:17 test1
-rw-r--r--. 1 root   root      0 May 14 19:10 test2
[root@slyoyo python_test]# tree copytree_copy/
copytree_copy/
└── test├── hahaha├── test1└── test2

实例

8  shutil.rmtree(path, ignore_errors=False, οnerrοr=None)   #递归地删除文件

def rmtree(path, ignore_errors=False, οnerrοr=None):"""Recursively delete a directory tree.If ignore_errors is set, errors are ignored; otherwise, if onerroris set, it is called to handle the error with arguments (func,path, exc_info) where func is platform and implementation dependent;path is the argument to that function that caused it to fail; andexc_info is a tuple returned by sys.exc_info().  If ignore_errorsis false and onerror is None, an exception is raised."""if ignore_errors:def onerror(*args):passelif onerror is None:def onerror(*args):raiseif _use_fd_functions:# While the unsafe rmtree works fine on bytes, the fd based does not.if isinstance(path, bytes):path = os.fsdecode(path)# Note: To guard against symlink races, we use the standard# lstat()/open()/fstat() trick.try:orig_st = os.lstat(path)except Exception:onerror(os.lstat, path, sys.exc_info())returntry:fd = os.open(path, os.O_RDONLY)except Exception:onerror(os.lstat, path, sys.exc_info())returntry:if os.path.samestat(orig_st, os.fstat(fd)):_rmtree_safe_fd(fd, path, onerror)try:os.rmdir(path)except OSError:onerror(os.rmdir, path, sys.exc_info())else:try:# symlinks to directories are forbidden, see bug #1669raise OSError("Cannot call rmtree on a symbolic link")except OSError:onerror(os.path.islink, path, sys.exc_info())finally:os.close(fd)else:return _rmtree_unsafe(path, onerror)# Allow introspection of whether or not the hardening against symlink
# attacks is supported on the current platform
rmtree.avoids_symlink_attacks = _use_fd_functions

查看源代码

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

def move(src, dst):"""Recursively move a file or directory to another location. This issimilar to the Unix "mv" command. Return the file or directory'sdestination.If the destination is a directory or a symlink to a directory, the sourceis moved inside the directory. The destination path must not alreadyexist.If the destination already exists but is not a directory, it may beoverwritten depending on os.rename() semantics.If the destination is on our current filesystem, then rename() is used.Otherwise, src is copied to the destination and then removed. Symlinks arerecreated under the new name if os.rename() fails because of crossfilesystem renames.A lot more could be done here...  A look at a mv.c shows a lot ofthe issues this implementation glosses over."""real_dst = dstif os.path.isdir(dst):if _samefile(src, dst):# We might be on a case insensitive filesystem,# perform the rename anyway.
            os.rename(src, dst)returnreal_dst = os.path.join(dst, _basename(src))if os.path.exists(real_dst):raise Error("Destination path '%s' already exists" % real_dst)try:os.rename(src, real_dst)except OSError:if os.path.islink(src):linkto = os.readlink(src)os.symlink(linkto, real_dst)os.unlink(src)elif os.path.isdir(src):if _destinsrc(src, dst):raise Error("Cannot move a directory '%s' into itself '%s'." % (src, dst))copytree(src, real_dst, symlinks=True)rmtree(src)else:copy2(src, real_dst)os.unlink(src)return real_dst

查看源代码

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

def make_archive(base_name, format, root_dir=None, base_dir=None, verbose=0,dry_run=0, owner=None, group=None, logger=None):"""Create an archive file (eg. zip or tar).'base_name' is the name of the file to create, minus any format-specificextension; 'format' is the archive format: one of "zip", "tar", "bztar"or "gztar".'root_dir' is a directory that will be the root directory of thearchive; ie. we typically chdir into 'root_dir' before creating thearchive.  'base_dir' is the directory where we start archiving from;ie. 'base_dir' will be the common prefix of all files anddirectories in the archive.  'root_dir' and 'base_dir' both defaultto the current directory.  Returns the name of the archive file.'owner' and 'group' are used when creating a tar archive. By default,uses the current owner and group."""save_cwd = os.getcwd()if root_dir is not None:if logger is not None:logger.debug("changing into '%s'", root_dir)base_name = os.path.abspath(base_name)if not dry_run:os.chdir(root_dir)if base_dir is None:base_dir = os.curdirkwargs = {'dry_run': dry_run, 'logger': logger}try:format_info = _ARCHIVE_FORMATS[format]except KeyError:raise ValueError("unknown archive format '%s'" % format)func = format_info[0]for arg, val in format_info[1]:kwargs[arg] = valif format != 'zip':kwargs['owner'] = ownerkwargs['group'] = grouptry:filename = func(base_name, base_dir, **kwargs)finally:if root_dir is not None:if logger is not None:logger.debug("changing back to '%s'", save_cwd)os.chdir(save_cwd)return filename

查看源代码

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

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

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

>>> shutil.make_archive('tarball','gztar',root_dir='copytree_test')[root@slyoyo python_test]# ls -l
total 12
drwxr-xr-x. 3 root   root   4096 May 14 19:36 copytree_copy
drwxr-xr-x. 3 root   root   4096 May 14 19:36 copytree_test
-rw-r--r--. 1 root   root      0 May 14 21:12 tarball.tar.gz
-rw-r--r--. 1 python python   79 May 14 05:17 test1
-rw-r--r--. 1 root   root      0 May 14 19:10 test2

实例

转载于:https://www.cnblogs.com/MnCu8261/p/5494807.html

python之模块之shutil模块相关推荐

  1. Python中os和shutil模块实用方法集锦

    Python中os和shutil模块实用方法集锦 类型:转载 时间:2014-05-13 这篇文章主要介绍了Python中os和shutil模块实用方法集锦,需要的朋友可以参考下 复制代码代码如下: ...

  2. python使用os和shutil模块进行文件创建,删除,移动,复制,重命名

    python使用os和shutil模块进行文件创建,删除,移动,复制,重命名 文章目录: 1 os模块的使用 1.1 os不带path 1.1.1 os.sep 属性:返回系统路径分隔符 1.1.2 ...

  3. python 文件操作 os模块和shutil模块

    转载自:http://www.cnblogs.com/rollenholt/archive/2012/04/23/2466179.html ############################## ...

  4. python shutil模块导入_python常用模块之shutil模块

    python常用模块之shutil模块 shutil模块,高级的文件.文件夹.压缩包处理模块 1.shutil.copyfile(src,des[,length]):将文件内容拷贝到另一个文件 In ...

  5. python bytes查找位置_Python进阶5---StringIO和BytesIO、路径操作、OS模块、shutil模块

    StringIO StringIO操作 BytesIO BytesIO操作 file-like对象 路径操作 路径操作模块 3.4版本之前:os.path模块 3.4版本开始 建议使用pathlib模 ...

  6. 随机模块random、os模块、sys模块、shutil模块

    随机模块random 随机模块的用法 >>> random.randrange(1,10) #返回1-10之间的一个随机数,不包括10 >>> random.ran ...

  7. shutil模块 python_python之模块之shutil模块

    shutil -- --High-level file operations  高级的文件操作模块. os模块提供了对目录或者文件的新建/删除/查看文件属性,还提供了对文件以及目录的路径操作.比如说: ...

  8. 模块讲解----shutil模块(copy、压缩、解压)

    作用与功能 主要用于文件的copy,压缩,解压 导入shuitl模块: import shutil copy方法 1 1.shutil.copyfileobj() 打开file1,并copy写入fil ...

  9. python shutil模块用法实例分析_Python shutil模块用法实例分析

    分享大神指教Python中的shutil模块的rmtree()方法如分享大神指教Python中的shutil模块的rmtree()方法如何实现.思路是怎样的rmtree() 是用来删除文件目录及其中的 ...

最新文章

  1. SAP MM IV中的Duplicated Invoice Check功能的测试
  2. 【GNN】一份完全解读:是什么使神经网络变成图神经网络?
  3. Linux修改主机名的方法
  4. vue + element ui 的后台管理系统框架_从零开始搭建 VUE + Element UI后台管理系统框架...
  5. SparkSQL操作Hive
  6. kettle从入门到精通_数据分析师的全景职业规划,入门、转行都先看这篇
  7. 如何在 Linux 上重命名一组文件
  8. jeecg导出Excel
  9. Dubbo框架协议总结
  10. 自定义C语言头文件书写格式
  11. JDK的发布周期缩短,JDK9,JDK10是短期版本
  12. UR5 UR10 ------六自由度机械臂
  13. win10家庭版升级为专业版
  14. 视频转换器如何将视频MKV转换成MP4格式 1
  15. 霸榜GitHub!程序员必懂的15大定律和7大原则
  16. java中string.length_Java 中的String length() 方法
  17. STM32CubeIDE加CubeMX开发二——CudeMX的使用
  18. ORB-SLAM3的Euroc数据集测试
  19. 自动化测试总结报告模板
  20. Python UnitTest接口自动化实战

热门文章

  1. PHP store session with couchbase
  2. Prism4文档翻译(第九章 第二部分)
  3. SuperMap IS.NET自定义Action添加Mark
  4. 使用ASP.NET 2.0 Profile存储用户信息
  5. index.wxss 导入不显示结果
  6. Leetcode-5199 Smallest String With Swaps(交换字符串中的元素)
  7. Spring框架学习3:bean元素属性
  8. idea多级目录不展开的问题
  9. 杂项:SVN 常用方法
  10. Python爬虫学习第一天--uillib库和request库