Python3 shutil模块
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python3 shutil模块相关的知识,希望对你有一定的参考价值。
平时我们总会用到复制文件的命令,Python中自带了相应模块,那就是shutil模块,下面是shutil模块的分析及用法。
1、copyfileobj(fsrc, fdst, length=16*1024)
将源文件拷贝到目标文件,每次拷贝16KB。这个方法中,原文件及目标文件并没有进行关闭,所以这是一个基本方法,并不经常使用。
1 def copyfileobj(fsrc, fdst, length=16*1024): 2 """copy data from file-like object fsrc to file-like object fdst""" 3 while 1: 4 buf = fsrc.read(length) 5 if not buf: 6 break 7 fdst.write(buf)
2、copyfile(src, dst, *, follow_symlinks=True)
拷贝源文件到目标文件,如果follow_symlinks项没有设定并且源文件是一个链接,则只拷贝连接,不拷贝指向的文件。
1 def copyfile(src, dst, *, follow_symlinks=True): 2 """Copy data from src to dst. 3 4 If follow_symlinks is not set and src is a symbolic link, a new 5 symlink will be created instead of copying the file it points to. 6 7 """ 8 if _samefile(src, dst): 9 raise SameFileError("{!r} and {!r} are the same file".format(src, dst)) 10 11 for fn in [src, dst]: 12 try: 13 st = os.stat(fn) 14 except OSError: 15 # File most likely does not exist 16 pass 17 else: 18 # XXX What about other special files? (sockets, devices...) 19 if stat.S_ISFIFO(st.st_mode): 20 raise SpecialFileError("`%s` is a named pipe" % fn) 21 22 if not follow_symlinks and os.path.islink(src): 23 os.symlink(os.readlink(src), dst) 24 else: 25 with open(src, ‘rb‘) as fsrc: 26 with open(dst, ‘wb‘) as fdst: 27 copyfileobj(fsrc, fdst) 28 return dst
3、copymode(src, dst, *, follow_symlinks=True)
仅拷贝文件权限,如果follow_symlinks项没有设定并且两个文件都是链接,如果lchmod(比如linux系统)不可用,那么这个方法也不可用。
1 def copymode(src, dst, *, follow_symlinks=True): 2 """Copy mode bits from src to dst. 3 4 If follow_symlinks is not set, symlinks aren‘t followed if and only 5 if both `src` and `dst` are symlinks. If `lchmod` isn‘t available 6 (e.g. Linux) this method does nothing. 7 8 """ 9 if not follow_symlinks and os.path.islink(src) and os.path.islink(dst): 10 if hasattr(os, ‘lchmod‘): 11 stat_func, chmod_func = os.lstat, os.lchmod 12 else: 13 return 14 elif hasattr(os, ‘chmod‘): 15 stat_func, chmod_func = os.stat, os.chmod 16 else: 17 return 18 19 st = stat_func(src) 20 chmod_func(dst, stat.S_IMODE(st.st_mode))
4、copystat(src, dst, *, follow_symlinks=True)
拷贝状态信息
1 def copystat(src, dst, *, follow_symlinks=True): 2 """Copy all stat info (mode bits, atime, mtime, flags) from src to dst. 3 4 If the optional flag `follow_symlinks` is not set, symlinks aren‘t followed if and 5 only if both `src` and `dst` are symlinks. 6 7 """ 8 def _nop(*args, ns=None, follow_symlinks=None): 9 pass 10 11 # follow symlinks (aka don‘t not follow symlinks) 12 follow = follow_symlinks or not (os.path.islink(src) and os.path.islink(dst)) 13 if follow: 14 # use the real function if it exists 15 def lookup(name): 16 return getattr(os, name, _nop) 17 else: 18 # use the real function only if it exists 19 # *and* it supports follow_symlinks 20 def lookup(name): 21 fn = getattr(os, name, _nop) 22 if fn in os.supports_follow_symlinks: 23 return fn 24 return _nop 25 26 st = lookup("stat")(src, follow_symlinks=follow) 27 mode = stat.S_IMODE(st.st_mode) 28 lookup("utime")(dst, ns=(st.st_atime_ns, st.st_mtime_ns), 29 follow_symlinks=follow) 30 try: 31 lookup("chmod")(dst, mode, follow_symlinks=follow) 32 except NotImplementedError: 33 # if we got a NotImplementedError, it‘s because 34 # * follow_symlinks=False, 35 # * lchown() is unavailable, and 36 # * either 37 # * fchownat() is unavailable or 38 # * fchownat() doesn‘t implement AT_SYMLINK_NOFOLLOW. 39 # (it returned ENOSUP.) 40 # therefore we‘re out of options--we simply cannot chown the 41 # symlink. give up, suppress the error. 42 # (which is what shutil always did in this circumstance.) 43 pass 44 if hasattr(st, ‘st_flags‘): 45 try: 46 lookup("chflags")(dst, st.st_flags, follow_symlinks=follow) 47 except OSError as why: 48 for err in ‘EOPNOTSUPP‘, ‘ENOTSUP‘: 49 if hasattr(errno, err) and why.errno == getattr(errno, err): 50 break 51 else: 52 raise 53 _copyxattr(src, dst, follow_symlinks=follow)
5、copy(src, dst, *, follow_symlinks=True)
拷贝文件及权限
1 def copy(src, dst, *, follow_symlinks=True): 2 """Copy data and mode bits ("cp src dst"). Return the file‘s destination. 3 4 The destination may be a directory. 5 6 If follow_symlinks is false, symlinks won‘t be followed. This 7 resembles GNU‘s "cp -P src dst". 8 9 If source and destination are the same file, a SameFileError will be 10 raised. 11 12 """ 13 if os.path.isdir(dst): 14 dst = os.path.join(dst, os.path.basename(src)) 15 copyfile(src, dst, follow_symlinks=follow_symlinks) 16 copymode(src, dst, follow_symlinks=follow_symlinks) 17 return dst
6、copy2(src, dst, *, follow_symlinks=True)
拷贝文件和状态信息
1 def copy2(src, dst, *, follow_symlinks=True): 2 """Copy data and all stat info ("cp -p src dst"). Return the file‘s 3 destination." 4 5 The destination may be a directory. 6 7 If follow_symlinks is false, symlinks won‘t be followed. This 8 resembles GNU‘s "cp -P src dst". 9 10 """ 11 if os.path.isdir(dst): 12 dst = os.path.join(dst, os.path.basename(src)) 13 copyfile(src, dst, follow_symlinks=follow_symlinks) 14 copystat(src, dst, follow_symlinks=follow_symlinks) 15 return dst
7、ignore_patterns(*patterns)
忽略特定文件。与递归拷贝等进行连用去除不需要操作的文件。
1 def ignore_patterns(*patterns): 2 """Function that can be used as copytree() ignore parameter. 3 4 Patterns is a sequence of glob-style patterns 5 that are used to exclude files""" 6 def _ignore_patterns(path, names): 7 ignored_names = [] 8 for pattern in patterns: 9 ignored_names.extend(fnmatch.filter(names, pattern)) 10 return set(ignored_names) 11 return _ignore_patterns
8、copytree(src, dst, symlinks=False, ignore=None, copy_function=copy2,ignore_dangling_symlinks=False)
递归拷贝文件
1 def copytree(src, dst, symlinks=False, ignore=None, copy_function=copy2, 2 ignore_dangling_symlinks=False): 3 """Recursively copy a directory tree. 4 5 The destination directory must not already exist. 6 If exception(s) occur, an Error is raised with a list of reasons. 7 8 If the optional symlinks flag is true, symbolic links in the 9 source tree result in symbolic links in the destination tree; if 10 it is false, the contents of the files pointed to by symbolic 11 links are copied. If the file pointed by the symlink doesn‘t 12 exist, an exception will be added in the list of errors raised in 13 an Error exception at the end of the copy process. 14 15 You can set the optional ignore_dangling_symlinks flag to true if you 16 want to silence this exception. Notice that this has no effect on 17 platforms that don‘t support os.symlink. 18 19 The optional ignore argument is a callable. If given, it 20 is called with the `src` parameter, which is the directory 21 being visited by copytree(), and `names` which is the list of 22 `src` contents, as returned by os.listdir(): 23 24 callable(src, names) -> ignored_names 25 26 Since copytree() is called recursively, the callable will be 27 called once for each directory that is copied. It returns a 28 list of names relative to the `src` directory that should 29 not be copied. 30 31 The optional copy_function argument is a callable that will be used 32 to copy each file. It will be called with the source path and the 33 destination path as arguments. By default, copy2() is used, but any 34 function that supports the same signature (like copy()) can be used. 35 36 """ 37 names = os.listdir(src) 38 if ignore is not None: 39 ignored_names = ignore(src, names) 40 else: 41 ignored_names = set() 42 43 os.makedirs(dst) 44 errors = [] 45 for name in names: 46 if name in ignored_names: 47 continue 48 srcname = os.path.join(src, name) 49 dstname = os.path.join(dst, name) 50 try: 51 if os.path.islink(srcname): 52 linkto = os.readlink(srcname) 53 if symlinks: 54 # We can‘t just leave it to `copy_function` because legacy 55 # code with a custom `copy_function` may rely on copytree 56 # doing the right thing. 57 os.symlink(linkto, dstname) 58 copystat(srcname, dstname, follow_symlinks=not symlinks) 59 else: 60 # ignore dangling symlink if the flag is on 61 if not os.path.exists(linkto) and ignore_dangling_symlinks: 62 continue 63 # otherwise let the copy occurs. copy2 will raise an error 64 if os.path.isdir(srcname): 65 copytree(srcname, dstname, symlinks, ignore, 66 copy_function) 67 else: 68 copy_function(srcname, dstname) 69 elif os.path.isdir(srcname): 70 copytree(srcname, dstname, symlinks, ignore, copy_function) 71 else: 72 # Will raise a SpecialFileError for unsupported file types 73 copy_function(srcname, dstname) 74 # catch the Error from the recursive copytree so that we can 75 # continue with other files 76 except Error as err: 77 errors.extend(err.args[0]) 78 except OSError as why: 79 errors.append((srcname, dstname, str(why))) 80 try: 81 copystat(src, dst) 82 except OSError as why: 83 # Copying file access times may fail on Windows 84 if getattr(why, ‘winerror‘, None) is None: 85 errors.append((src, dst, str(why))) 86 if errors: 87 raise Error(errors) 88 return dst 89 90 # version vulnerable to race conditions
9、rmtree(path, ignore_errors=False, onerror=None)
递归的删除文件
1 def rmtree(path, ignore_errors=False, onerror=None): 2 """Recursively delete a directory tree. 3 4 If ignore_errors is set, errors are ignored; otherwise, if onerror 5 is set, it is called to handle the error with arguments (func, 6 path, exc_info) where func is platform and implementation dependent; 7 path is the argument to that function that caused it to fail; and 8 exc_info is a tuple returned by sys.exc_info(). If ignore_errors 9 is false and onerror is None, an exception is raised. 10 11 """ 12 if ignore_errors: 13 def onerror(*args): 14 pass 15 elif onerror is None: 16 def onerror(*args): 17 raise 18 if _use_fd_functions: 19 # While the unsafe rmtree works fine on bytes, the fd based does not. 20 if isinstance(path, bytes): 21 path = os.fsdecode(path) 22 # Note: To guard against symlink races, we use the standard 23 # lstat()/open()/fstat() trick. 24 try: 25 orig_st = os.lstat(path) 26 except Exception: 27 onerror(os.lstat, path, sys.exc_info()) 28 return 29 try: 30 fd = os.open(path, os.O_RDONLY) 31 except Exception: 32 onerror(os.lstat, path, sys.exc_info()) 33 return 34 try: 35 if os.path.samestat(orig_st, os.fstat(fd)): 36 _rmtree_safe_fd(fd, path, onerror) 37 try: 38 os.rmdir(path) 39 except OSError: 40 onerror(os.rmdir, path, sys.exc_info()) 41 else: 42 try: 43 # symlinks to directories are forbidden, see bug #1669 44 raise OSError("Cannot call rmtree on a symbolic link") 45 except OSError: 46 onerror(os.path.islink, path, sys.exc_info()) 47 finally: 48 os.close(fd) 49 else: 50 return _rmtree_unsafe(path, onerror)
10、move(src, dst, copy_function=copy2)
递归的移动文件
1 def move(src, dst, copy_function=copy2): 2 """Recursively move a file or directory to another location. This is 3 similar to the Unix "mv" command. Return the file or directory‘s 4 destination. 5 6 If the destination is a directory or a symlink to a directory, the source 7 is moved inside the directory. The destination path must not already 8 exist. 9 10 If the destination already exists but is not a directory, it may be 11 overwritten depending on os.rename() semantics. 12 13 If the destination is on our current filesystem, then rename() is used. 14 Otherwise, src is copied to the destination and then removed. Symlinks are 15 recreated under the new name if os.rename() fails because of cross 16 filesystem renames. 17 18 The optional `copy_function` argument is a callable that will be used 19 to copy the source or it will be delegated to `copytree`. 20 By default, copy2() is used, but any function that supports the same 21 signature (like copy()) can be used. 22 23 A lot more could be done here... A look at a mv.c shows a lot of 24 the issues this implementation glosses over. 25 26 """ 27 real_dst = dst 28 if os.path.isdir(dst): 29 if _samefile(src, dst): 30 # We might be on a case insensitive filesystem, 31 # perform the rename anyway. 32 os.rename(src, dst) 33 return 34 35 real_dst = os.path.join(dst, _basename(src)) 36 if os.path.exists(real_dst): 37 raise Error("Destination path ‘%s‘ already exists" % real_dst) 38 try: 39 os.rename(src, real_dst) 40 except OSError: 41 if os.path.islink(src): 42 linkto = os.readlink(src) 43 os.symlink(linkto, real_dst) 44 os.unlink(src) 45 elif os.path.isdir(src): 46 if _destinsrc(src, dst): 47 raise Error("Cannot move a directory ‘%s‘ into itself" 48 " ‘%s‘." % (src, dst)) 49 copytree(src, real_dst, copy_function=copy_function, 50 symlinks=True) 51 rmtree(src) 52 else: 53 copy_function(src, real_dst) 54 os.unlink(src) 55 return real_dst
11、get_archive_formats()
返回用于存档支持的格式
1 def get_archive_formats(): 2 """Returns a list of supported formats for archiving and unarchiving. 3 4 Each element of the returned sequence is a tuple (name, description) 5 """ 6 formats = [(name, registry[2]) for name, registry in 7 _ARCHIVE_FORMATS.items()] 8 formats.sort() 9 return formats
12、register_archive_format(name, function, extra_args=None, description=‘‘)
注册档案格式(没有使用过),可以自定义压缩种类、调用程序以及相关描述。调用get_archive_formats()会返回相应数据。
1 def register_archive_format(name, function, extra_args=None, description=‘‘): 2 """Registers an archive format. 3 4 name is the name of the format. function is the callable that will be 5 used to create archives. If provided, extra_args is a sequence of 6 (name, value) tuples that will be passed as arguments to the callable. 7 description can be provided to describe the format, and will be returned 8 by the get_archive_formats() function. 9 """ 10 if extra_args is None: 11 extra_args = [] 12 if not callable(function): 13 raise TypeError(‘The %s object is not callable‘ % function) 14 if not isinstance(extra_args, (tuple, list)): 15 raise TypeError(‘extra_args needs to be a sequence‘) 16 for element in extra_args: 17 if not isinstance(element, (tuple, list)) or len(element) !=2: 18 raise TypeError(‘extra_args elements are : (arg_name, value)‘) 19 20 _ARCHIVE_FORMATS[name] = (function, extra_args, description)
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:日志记录
1 def make_archive(base_name, format, root_dir=None, base_dir=None, verbose=0, 2 dry_run=0, owner=None, group=None, logger=None): 3 """Create an archive file (eg. zip or tar). 4 5 ‘base_name‘ is the name of the file to create, minus any format-specific 6 extension; ‘format‘ is the archive format: one of "zip", "tar", "bztar" 7 or "gztar". 8 9 ‘root_dir‘ is a directory that will be the root directory of the 10 archive; ie. we typically chdir into ‘root_dir‘ before creating the 11 archive. ‘base_dir‘ is the directory where we start archiving from; 12 ie. ‘base_dir‘ will be the common prefix of all files and 13 directories in the archive. ‘root_dir‘ and ‘base_dir‘ both default 14 to the current directory. Returns the name of the archive file. 15 16 ‘owner‘ and ‘group‘ are used when creating a tar archive. By default, 17 uses the current owner and group. 18 """ 19 save_cwd = os.getcwd() 20 if root_dir is not None: 21 if logger is not None: 22 logger.debug("changing into ‘%s‘", root_dir) 23 base_name = os.path.abspath(base_name) 24 if not dry_run: 25 os.chdir(root_dir) 26 27 if base_dir is None: 28 base_dir = os.curdir 29 30 kwargs = {‘dry_run‘: dry_run, ‘logger‘: logger} 31 32 try: 33 format_info = _ARCHIVE_FORMATS[format] 34 except KeyError: 35 raise ValueError("unknown archive format ‘%s‘" % format) 36 37 func = format_info[0] 38 for arg, val in format_info[1]: 39 kwargs[arg] = val 40 41 if format != ‘zip‘: 42 kwargs[‘owner‘] = owner 43 kwargs[‘group‘] = group 44 45 try: 46 filename = func(base_name, base_dir, **kwargs) 47 finally: 48 if root_dir is not None: 49 if logger is not None: 50 logger.debug("changing back to ‘%s‘", save_cwd) 51 os.chdir(save_cwd) 52 53 return filename
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)
解压缩命令,没有返回值
1 def unpack_archive(filename, extract_dir=None, format=None): 2 """Unpack an archive. 3 4 `filename` is the name of the archive. 5 6 `extract_dir` is the name of the target directory, where the archive 7 is unpacked. If not provided, the current working directory is used. 8 9 `format` is the archive format: one of "zip", "tar", or "gztar". Or any 10 other registered format. If not provided, unpack_archive will use the 11 filename extension and see if an unpacker was registered for that 12 extension. 13 14 In case none is found, a ValueError is raised. 15 """ 16 if extract_dir is None: 17 extract_dir = os.getcwd() 18 19 if format is not None: 20 try: 21 format_info = _UNPACK_FORMATS[format] 22 except KeyError: 23 raise ValueError("Unknown unpack format ‘{0}‘".format(format)) 24 25 func = format_info[1] 26 func(filename, extract_dir, **dict(format_info[2])) 27 else: 28 # we need to look at the registered unpackers supported extensions 29 format = _find_unpack_format(filename) 30 if format is None: 31 raise ReadError("Unknown archive format ‘{0}‘".format(filename)) 32 33 func = _UNPACK_FORMATS[format][1] 34 kwargs = dict(_UNPACK_FORMATS[format][2]) 35 func(filename, extract_dir, **kwargs)
19、chown(path, user=None, group=None)
改变文件或目录的用户及属组信息
1 def chown(path, user=None, group=None): 2 """Change owner user and group of the given path. 3 4 user and group can be the uid/gid or the user/group names, and in that case, 5 they are converted to their respective uid/gid. 6 """ 7 8 if user is None and group is None: 9 raise ValueError("user and/or group must be set") 10 11 _user = user 12 _group = group 13 14 # -1 means don‘t change it 15 if user is None: 16 _user = -1 17 # user can either be an int (the uid) or a string (the system username) 18 elif isinstance(user, str): 19 _user = _get_uid(user) 20 if _user is None: 21 raise LookupError("no such user: {!r}".format(user)) 22 23 if group is None: 24 _group = -1 25 elif not isinstance(group, int): 26 _group = _get_gid(group) 27 if _group is None: 28 raise LookupError("no such group: {!r}".format(group)) 29 30 os.chown(path, _user, _group)
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