python-shutil模块⼀、简介
shutil是⾼级的⽂件、⽂件夹、压缩包处理模块
⼆使⽤
①、pyfileobj(fsrc, fdst[, length])
将⽂件内容拷贝到另⼀个⽂件中,可以指定⽂件⼤⼩。
注意:fsrc和fdst都是⽂件对象,拷贝的时候需要先把两个⽂件都打开
我们先来看下源码:
def copyfileobj(fsrc, fdst, length=16*1024):
"""copy data from file-like object fsrc to file-like object fdst"""
while 1:
buf = ad(length)
if not buf:
break
fdst.write(buf)
实例:
import shutil
②、pyfile(src, dst)
拷贝⽂件
源码:
def copyfile(src, dst, *, follow_symlinks=True):
soy"""Copy data from src to dst.
If follow_symlinks is not t and src is a symbolic link, a new
symlink will be created instead of copying the file it points to.
"""
if _samefile(src, dst):
rai 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
el:
# XXX What about other special files? (sockets, )
if stat.S_ISFIFO(st.st_mode):
rai SpecialFileError("`%s` is a named pipe" % fn)
if not follow_symlinks and os.path.islink(src):
os.adlink(src), dst)
el:
with open(src, 'rb') as fsrc:
with open(dst, 'wb') as fdst:
copyfileobj(fsrc, fdst)
return dst
实例:
import shutil
③、pymode(src,dst)
拷贝权限内容、组、⽤户均不变
源码:
def copymode(src, dst, *, follow_symlinks=True):
"""Copy mode bits from src to dst.
If follow_symlinks is not t, 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
greedisgoodel:
return
涨粉丝1元1000个活粉elif hasattr(os, 'chmod'):
stat_func, chmod_func = os.stat, os.chmod
el:
return
st = stat_func(src)
chmod_func(dst, stat.S_IMODE(st.st_mode))
实例:
import shutil
④、pystat(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 t, 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:
# u the real function if it exists
def lookup(name):
return getattr(os, name, _nop)
el:
# u 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 becau
# * follow_symlinks=Fal,
# * 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) == getattr(errno, err):
break
el:
rai
_copyxattr(src, dst, follow_symlinks=follow)
⑤、 py(src, dst)
拷贝⽂件和权限
源码:
北洋燕园
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 fal, symlinks won't be followed. This
rembles GNU's "cp -P src dst".
If source and destination are the same file, a SameFileError will be
raid.
"""
if os.path.isdir(dst):
dst = os.path.join(dst, os.path.baname(src))
copyfile(src, dst, follow_symlinks=follow_symlinks)
copymode(src, dst, follow_symlinks=follow_symlinks)
return dst
⑥py2(src, dst)
拷贝⽂件和状态信息
源码:
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 fal, symlinks won't be followed. This
rembles GNU's "cp -P src dst".
"""
if os.path.isdir(dst):
dst = os.path.join(dst, os.path.baname(src))
copyfile(src, dst, follow_symlinks=follow_symlinks)
copystat(src, dst, follow_symlinks=follow_symlinks)
return dst
⑦pytree(src, dst, symlinks=Fal, ignore=None)
递归的去拷贝⽂件18hour
源码:
def copytree(src, dst, symlinks=Fal, ignore=None, copy_function=copy2, ignore_dangling_symlinks=Fal):
"""Recursively copy a directory tree.
The destination directory must not already exist.
If exception(s) occur, an Error is raid 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 fal, 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 raid in
an Error exception at the end of the copy process.
You can t 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 ofraper的中文意思是什么
`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 ud
beguileto copy each file. It will be called with the source path and the
destination path as arguments. By default, copy2() is ud, but any
function that supports the same signature (like copy()) can be ud.
"""
names = os.listdir(src)
if ignore is not None:
ignored_names = ignore(src, names)
el:
ignored_names = t()
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` becau 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) el:
# ignore dangling symlink if the flag is on
if not ists(linkto) and ignore_dangling_symlinks: continue
# otherwi let the copy occurs. copy2 will rai an error
if os.path.isdir(srcname):
copytree(srcname, dstname, symlinks, ignore,
copy_function)
el:
copy_function(srcname, dstname)
elif os.path.isdir(srcname):
copytree(srcname, dstname, symlinks, ignore, copy_function) el:
# Will rai 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:
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:
rai Error(errors)
return dst
# version vulnerable to race conditions
⑧、(path[, ignore_errors[, onerror]])
递归地去删除⽂件
源码:
def rmtree(path, ignore_errors=Fal, onerror=None):
"""Recursively delete a directory tree.
If ignore_errors is t, errors are ignored; otherwi, if onerror
is t, 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 caud it to fail; and
exc_info is a tuple returned _info(). If ignore_errors
is fal and onerror is None, an exception is raid.
"""
if ignore_errors:
def onerror(*args):
pass
elif onerror is None:
def onerror(*args):
rai
if _u_fd_functions:
# While the unsafe rmtree works fine on bytes, the fd bad does not. if isinstance(path, bytes):
path = os.fsdecode(path)
# Note: To guard against symlink races, we u the standard
# lstat()/open()/fstat() trick.
try:
orig_st = os.lstat(path)
except Exception:
onerror(os.lstat, path, _info())
return
try:
fd = os.open(path, os.O_RDONLY)
except Exception:
onerror(os.lstat, path, _info())
return
try:
if os.path.samestat(orig_st, os.fstat(fd)):
_rmtree_safe_fd(fd, path, onerror)
try:
except OSError:
dir, path, _info())
el:
try:
# symlinks to directories are forbidden, e bug #1669
rai OSError("Cannot call rmtree on a symbolic link")
except OSError:
onerror(os.path.islink, path, _info())
finally:
os.clo(fd)
el:
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 = _u_fd_functions
⑨、ve(src, dst)
递归的移动⽂件
def move(src, dst):
"""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 ame() mantics.
If the destination is on our current filesystem, then rename() is ud.
Otherwi, src is copied to the destination and then removed. Symlinks are