Python3 shutil模块
平时我们总会用到复制文件的命令,Python中自带了相应模块,那就是shutil模块,下面是shutil模块的分析及用法。
1、copyfileobj(fsrc, fdst, length=16*1024)
将源文件拷贝到目标文件,每次拷贝16KB。这个方法中,原文件及目标文件并没有进行关闭,所以这是一个基本方法,并不经常使用。
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)
source code
2、copyfile(src, dst, *, follow_symlinks=True)
拷贝源文件到目标文件,如果follow_symlinks项没有设定并且源文件是一个链接,则只拷贝连接,不拷贝指向的文件。
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 new
symlink 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 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) 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
source code
3、copymode(src, dst, *, follow_symlinks=True)
仅拷贝文件权限,如果follow_symlinks项没有设定并且两个文件都是链接,如果lchmod(比如linux系统)不可用,那么这个方法也不可用。
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 only
if 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.lchmod
else:
return
elif hasattr(os, 'chmod'):
stat_func, chmod_func = os.stat, os.chmod
else:
return st = stat_func(src)
chmod_func(dst, stat.S_IMODE(st.st_mode))
source code
4、copystat(src, dst, *, follow_symlinks=True)
拷贝状态信息
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 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_symlinks or not (os.path.islink(src) and os.path.islink(dst))
if follow:
# use the real function if it exists
def lookup(name):
return getattr(os, name, _nop)
else:
# use the real function only if it exists
# *and* it supports follow_symlinks
def lookup(name):
fn = getattr(os, name, _nop)
if fn in os.supports_follow_symlinks:
return fn
return _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)
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.)
pass
if 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):
break
else:
raise
_copyxattr(src, dst, follow_symlinks=follow)
source code
5、copy(src, dst, *, follow_symlinks=True)
拷贝文件及权限
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. This
resembles GNU's "cp -P src dst". If source and destination are the same file, a SameFileError will be
raised. """
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
source code
6、copy2(src, dst, *, follow_symlinks=True)
拷贝文件和状态信息
def copy2(src, dst, *, follow_symlinks=True):
"""Copy data and all stat info ("cp -p src dst"). Return the file's
destination." The destination may be a directory. If follow_symlinks is false, symlinks won't be followed. This
resembles 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
source code
7、ignore_patterns(*patterns)
忽略特定文件。与递归拷贝等进行连用去除不需要操作的文件。
def ignore_patterns(*patterns):
"""Function that can be used as copytree() ignore parameter. Patterns is a sequence of glob-style patterns
that are used to exclude files"""
def _ignore_patterns(path, names):
ignored_names = []
for pattern in patterns:
ignored_names.extend(fnmatch.filter(names, pattern))
return set(ignored_names)
return _ignore_patterns
source code
8、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 the
source tree result in symbolic links in the destination tree; if
it is false, the contents of the files pointed to by symbolic
links are copied. If the file pointed by the symlink doesn't
exist, an exception will be added in the list of errors raised in
an Error exception at the end of the copy process. You can set the optional ignore_dangling_symlinks flag to true if you
want to silence this exception. Notice that this has no effect on
platforms that don't support os.symlink. The optional ignore argument is a callable. If given, it
is called with the `src` parameter, which is the directory
being visited by copytree(), and `names` which is the list of
`src` contents, as returned by os.listdir(): callable(src, names) -> ignored_names Since copytree() is called recursively, the callable will be
called once for each directory that is copied. It returns a
list of names relative to the `src` directory that should
not be copied. The optional copy_function argument is a callable that will be used
to copy each file. It will be called with the source path and the
destination path as arguments. By default, copy2() is used, but any
function 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:
continue
srcname = 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 on
if not os.path.exists(linkto) and ignore_dangling_symlinks:
continue
# otherwise let the copy occurs. copy2 will raise an error
if 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 files
except 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 Windows
if getattr(why, 'winerror', None) is None:
errors.append((src, dst, str(why)))
if errors:
raise Error(errors)
return dst # version vulnerable to race conditions
source code
9、rmtree(path, ignore_errors=False, onerror=None)
递归的删除文件
def rmtree(path, ignore_errors=False, onerror=None):
"""Recursively delete a directory tree. If ignore_errors is set, errors are ignored; otherwise, if onerror
is 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; and
exc_info is a tuple returned by sys.exc_info(). If ignore_errors
is false and onerror is None, an exception is raised. """
if ignore_errors:
def onerror(*args):
pass
elif onerror is None:
def onerror(*args):
raise
if _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())
return
try:
fd = os.open(path, os.O_RDONLY)
except Exception:
onerror(os.lstat, path, sys.exc_info())
return
try:
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 #1669
raise 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)
source code
10、move(src, dst, copy_function=copy2)
递归的移动文件
def move(src, dst, copy_function=copy2):
"""Recursively move a file or directory to another location. This is
similar to the Unix "mv" command. Return the file or directory's
destination. If the destination is a directory or a symlink to a directory, the source
is moved inside the directory. The destination path must not already
exist. If the destination already exists but is not a directory, it may be
overwritten 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 are
recreated under the new name if os.rename() fails because of cross
filesystem renames. The optional `copy_function` argument is a callable that will be used
to copy the source or it will be delegated to `copytree`.
By default, copy2() is used, but any function that supports the same
signature (like copy()) can be used. A lot more could be done here... A look at a mv.c shows a lot of
the issues this implementation glosses over. """
real_dst = dst
if os.path.isdir(dst):
if _samefile(src, dst):
# We might be on a case insensitive filesystem,
# perform the rename anyway.
os.rename(src, dst)
return real_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, copy_function=copy_function,
symlinks=True)
rmtree(src)
else:
copy_function(src, real_dst)
os.unlink(src)
return real_dst
source code
11、get_archive_formats()
返回用于存档支持的格式
def get_archive_formats():
"""Returns a list of supported formats for archiving and unarchiving. Each element of the returned sequence is a tuple (name, description)
"""
formats = [(name, registry[2]) for name, registry in
_ARCHIVE_FORMATS.items()]
formats.sort()
return formats
source code
12、register_archive_format(name, function, extra_args=None, description='')
注册档案格式(没有使用过),可以自定义压缩种类、调用程序以及相关描述。调用get_archive_formats()会返回相应数据。
def register_archive_format(name, function, extra_args=None, description=''):
"""Registers an archive format. name is the name of the format. function is the callable that will be
used to create archives. If provided, extra_args is a sequence of
(name, value) tuples that will be passed as arguments to the callable.
description can be provided to describe the format, and will be returned
by the get_archive_formats() function.
"""
if extra_args is None:
extra_args = []
if not callable(function):
raise TypeError('The %s object is not callable' % function)
if not isinstance(extra_args, (tuple, list)):
raise TypeError('extra_args needs to be a sequence')
for element in extra_args:
if not isinstance(element, (tuple, list)) or len(element) !=2:
raise TypeError('extra_args elements are : (arg_name, value)') _ARCHIVE_FORMATS[name] = (function, extra_args, description)
source code
13、unregister_archive_format(name)
删除压缩包种类
14、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”“gztar”
root_dir:要压缩文件夹路径(默认当前目录)
owner:用户,默认为当前用户
group:组,默认为当前组
logger:日志记录
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-specific
extension; 'format' is the archive format: one of "zip", "tar", "bztar"
or "gztar". 'root_dir' is a directory that will be the root directory of the
archive; ie. we typically chdir into 'root_dir' before creating the
archive. 'base_dir' is the directory where we start archiving from;
ie. 'base_dir' will be the common prefix of all files and
directories in the archive. 'root_dir' and 'base_dir' both default
to 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.curdir kwargs = {'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] = val if format != 'zip':
kwargs['owner'] = owner
kwargs['group'] = group try:
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
source code
15、get_unpack_formats()
返回解压缩包的类型
16、register_unpack_format(name, extensions, function, extra_args=None,description='')
注册解压缩包的类型
17、unregister_unpack_format(name)
取消解压缩包类型的注册
18、unpack_archive(filename, extract_dir=None, format=None)
解压缩命令,没有返回值
def unpack_archive(filename, extract_dir=None, format=None):
"""Unpack an archive. `filename` is the name of the archive. `extract_dir` is the name of the target directory, where the archive
is unpacked. If not provided, the current working directory is used. `format` is the archive format: one of "zip", "tar", or "gztar". Or any
other registered format. If not provided, unpack_archive will use the
filename extension and see if an unpacker was registered for that
extension. In case none is found, a ValueError is raised.
"""
if extract_dir is None:
extract_dir = os.getcwd() if format is not None:
try:
format_info = _UNPACK_FORMATS[format]
except KeyError:
raise ValueError("Unknown unpack format '{0}'".format(format)) func = format_info[1]
func(filename, extract_dir, **dict(format_info[2]))
else:
# we need to look at the registered unpackers supported extensions
format = _find_unpack_format(filename)
if format is None:
raise ReadError("Unknown archive format '{0}'".format(filename)) func = _UNPACK_FORMATS[format][1]
kwargs = dict(_UNPACK_FORMATS[format][2])
func(filename, extract_dir, **kwargs)
source code
19、chown(path, user=None, group=None)
改变文件或目录的用户及属组信息
def chown(path, user=None, group=None):
"""Change owner user and group of the given path. user and group can be the uid/gid or the user/group names, and in that case,
they are converted to their respective uid/gid.
""" if user is None and group is None:
raise ValueError("user and/or group must be set") _user = user
_group = group # -1 means don't change it
if user is None:
_user = -1
# user can either be an int (the uid) or a string (the system username)
elif isinstance(user, str):
_user = _get_uid(user)
if _user is None:
raise LookupError("no such user: {!r}".format(user)) if group is None:
_group = -1
elif not isinstance(group, int):
_group = _get_gid(group)
if _group is None:
raise LookupError("no such group: {!r}".format(group)) os.chown(path, _user, _group)
source code
20、get_terminal_size(fallback=(80, 24))
获取终端大小,默认为(80,24)
21、which(cmd, mode=os.F_OK | os.X_OK, path=None)
返回命令的路径,可以自定义路径,否则使用os.environ.get(“PATH”)路径。如果没有找到返回None
Python3 shutil模块的更多相关文章
- s14 第5天 时间模块 随机模块 String模块 shutil模块(文件操作) 文件压缩(zipfile和tarfile)shelve模块 XML模块 ConfigParser配置文件操作模块 hashlib散列模块 Subprocess模块(调用shell) logging模块 正则表达式模块 r字符串和转译
时间模块 time datatime time.clock(2.7) time.process_time(3.3) 测量处理器运算时间,不包括sleep时间 time.altzone 返回与UTC时间 ...
- Python第二十天 shutil 模块 zipfile tarfile 模块
Python第二十天 shutil 模块 zipfile tarfile 模块 os文件的操作还应该包含移动 复制 打包 压缩 解压等操作,这些os模块都没有提供 shutil 模块shut ...
- python中的shutil模块
目录 python中的shutil模块 目录和文件操作 归档操作 python中的shutil模块 shutil模块对文件和文件集合提供了许多高级操作,特别是提供了支持文件复制和删除的函数. 目录和文 ...
- Python进阶5---StringIO和BytesIO、路径操作、OS模块、shutil模块
StringIO StringIO操作 BytesIO BytesIO操作 file-like对象 路径操作 路径操作模块 3.4版本之前:os.path模块 3.4版本开始 建议使用pathlib模 ...
- shutil模块和os模块对比
一.shutil -- 是一种高层次的文件操作工具类似于高级API,而且主要强大之处在于其对文件的复制与删除操作更是比较支持好. 1.shutil.copy(src,dst)复制一个文件到另一个目录下 ...
- python之shutil模块详解
shutil模块 -- --High-level file operations 高级的文件操作模块. os模块提供了对目录或者文件的新建/删除/查看文件属性,还提供了对文件以及目录的路径操作.比如 ...
- 常用模块 - shutil模块
一.简介 shutil – Utility functions for copying and archiving files and directory trees.(用于复制和存档文件和目录树的实 ...
- sys模块和shutil模块
一.sys模块 常用方法有: #!/usr/bin/env python3 #-*- coding:utf-8 -*- # write by congcong import sys # 命令行参数Li ...
- 包与time,datetime,random,sys,shutil 模块
一.包 包是什么? 包是一种通过使用‘.模块名’来组织python模块名称空间的方式. 注意: 1. 在python3中,即使包下没有__init__.py文件,import 包仍然不会报错,而在py ...
随机推荐
- JavaScript权威指南--类型、值和变量
本章要点图 数据类型:计算机程序的运行需要对值(value)比如数字3.14或者文本"hello world"进行操作,在编程语言中,能够表示并操作的值的类型叫做数据类型(type ...
- 使用@media screen解决移动web开发的多分辨率问题
当今移动设备的发展已经越来越迅速,移动web开发的需求也越来越多多.许多大平台.大门户都纷纷推出了自己的移动web版网站. 随着移动设备飞速的发展,移动产品的屏幕规格越来越多.从几年前的320×240 ...
- Weex了解
weex描述 weex是一个使用web开发体验来开发高性能原生应用的框架,能支持vue.js框架.它可以实现用同一套代码来构建Andriod.IOS和web应用.可以实现使用JavaScript和流行 ...
- spoj-ANARC05H -dp
ANARC05H - Chop Ahoy! Revisited! #dynamic-programming Given a non-empty string composed of digits on ...
- day36 爬虫+http请求+高性能
爬虫 参考博客:http://www.cnblogs.com/wupeiqi/articles/5354900.html http://www.cnblogs.com/wupeiqi/articles ...
- mysqldb 安装
MySQLdb是python的一个标准的连接和操纵mysql的模块. ubuntu下安装: sudo apt-get install python-mysqldb sudo apt-get insta ...
- log4j 日志详解
# 以下是rootLogger的配置,子类默认继承,但是子类重写下面配置=rootLogger+自己配置,我晕#输出到控制台 log4j.appender.console=org.apache.log ...
- Quartz教程:快速入门
原文链接 | 译文链接 | 翻译:nkcoder | 校对:方腾飞 本系列教程由quartz-2.2.x官方文档翻译.整理而来,希望给同样对quartz感兴趣的朋友一些参考和帮助,有任何不当或错误之处 ...
- hdu 4081 Qin Shi Huang's National Road System 树的基本性质 or 次小生成树思想 难度:1
During the Warring States Period of ancient China(476 BC to 221 BC), there were seven kingdoms in Ch ...
- ElementUI组件Cascader级联选择器数据后台处理
Cascader级联选择器数据数据格式不知道的可以去官网看下:这里我就不表示什么了. 部门实体类: import lombok.Data; @Data public class Department ...