Python Shutil Module

Source: Internet
Author: User
Tags extend symlink

Shutil Module

Advanced files, folders, Compression pack processing modules

Copyfileobj

Shutil.copyfileobj (FSRC, fdst[, length])
Copy the contents of the file to another file, which can be part of the content

def copyfileobj (FSRC, FDST, length=16*1024): "" "    copy data from File-like object FSRC to File-like object Fdst" ""    W Hile 1:        buf = fsrc.read (length)        if not buf:            break        fdst.write (BUF)

CopyFile

Shutil.copyfile (SRC, DST)
Copy Files

def copyfile (SRC, DST): "" "    Copy data from src to DST" ""    if _samefile (SRC, DST):        Raise Error ("'%s ' and '%s ' is The same file "% (src, DST)) for    fn in [SRC, DST]:        try:            st = Os.stat (FN)        except OSError:            # File most Likely does not exist            pass        else: # XXX, what's on other            special files? (Sockets, devices ...)            If Stat. S_isfifo (St.st_mode):                Raise Specialfileerror ("'%s ' is a named pipe"% fn)    with open (SRC, ' RB ') as FSRC:        WI Th open (DST, ' WB ') as FDST:            copyfileobj (FSRC, FDST)

Copymode

Shutil.copymode (SRC, DST)
Copy permissions only. Content, group, user are not changed

def copymode (SRC, DST): "" "    Copy mode bits from src to DST" ""    if Hasattr (OS, ' chmod '):        st = Os.stat (src)        mo De = Stat. S_imode (St.st_mode)        os.chmod (DST, mode)

Copystat

Shutil.copystat (SRC, DST)
Information on the status of the copy, including: mode bits, Atime, mtime, Flags

def copystat (SRC, DST): "" "    Copy all stat info (mode bits, Atime, mtime, flags) from SRC to DST" ""    st = Os.stat (src )    mode = Stat. S_imode (St.st_mode)    if hasattr (OS, ' Utime '):        os.utime (DST, (St.st_atime, st.st_mtime))    if hasattr (OS, ' chmod '):        os.chmod (DST, mode)    if hasattr (OS, ' Chflags ') and hasattr (St, ' St_flags '):        try:            os.chflags ( DST, st.st_flags)        except OSError, why: For            err in ' Eopnotsupp ', ' enotsup ':                if Hasattr (errno, err) and why. errno = = GetAttr (errno, err): Break            Else:                raise

Copy

Shutil.copy (SRC, DST)
Copying files and Permissions

def copy (SRC, DST): "" "    copy data and mode bits (" cp src DST ").    The destination may be a directory.    "" " If Os.path.isdir (DST):        DST = os.path.join (DST, Os.path.basename (SRC))    copyfile (src, DST)    Copymode (SRC, Dst

Copy2

Shutil.copy2 (SRC, DST)
Copying files and status information

def copy2 (SRC, DST): "" "    Copy data and all stat info (" cp-p src DST ").    The destination may be a directory.    "" " If Os.path.isdir (DST):        DST = os.path.join (DST, Os.path.basename (SRC))    copyfile (src, DST)    Copystat (SRC, Dst

ignore_patterns/Copytree

Shutil.ignore_patterns (*patterns)
Shutil.copytree (SRC, DST, Symlinks=false, Ignore=none)
Recursive de-Copying files

Example: Copytree (source, Destination, ignore=ignore_patterns (' *.pyc ', ' tmp* '))

def ignore_patterns (*patterns): "" "Function that can used as copytree () ignore parameter.        Patterns is a sequence of Glob-style Patterns that was 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_patternsdef copytree (SRC, DST, Symlinks=false, Ignore=none): "" "recur    sively Copy a directory tree using Copy2 ().    The destination directory must not already exist.    If exception (s) occur, an Error was 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 TR Ee    If it is false, the contents of the files pointed through symbolic links is copied. The optional ignore argument is a callable. If given, it is called with the ' src ' parameter, which are the directory being visited by Copytree (), and ' names ' which are the list of ' src ' contents, as returned by Os.listdir (): Callable (SRC, names), Igno Red_names Since Copytree () is called recursively, the callable would be a called once for each directory this is copied .    It returns a list of names relative to the ' src ' directory of this should not being copied.    XXX Consider this example code rather than the ultimate tool. "" "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:contin UE SrcName = os.path.join (src, name) DstName = Os.path.join (DST, name) Try:if symlinks an            D Os.path.islink (srcname): Linkto = Os.readlink (srcname) os.symlink (Linkto, DstName) Elif Os.path.isdir (SrcName): Copytree (SrcName, DstName, symlinks, ignore) ElSE: # would raise a specialfileerror for unsupported file types Copy2 (SrcName, DstName) # Catch the error from the recursive copytree so, we can # continue with other files except Error, err : Errors.extend (Err.args[0]) except EnvironmentError, Why:errors.append (SrcName, DstName, S  TR (why))) Try:copystat (SRC, DST) except OSError, Why:if Windowserror are not None and isinstance (Why, Windowserror): # Copying file access times may fail on Windows pass else:errors.   Append (src, DST, str (why))) if Errors:raise Error, errors

Rmtree

Shutil.rmtree (path[, ignore_errors[, OnError])
To delete a file recursively

def rmtree (Path, Ignore_errors=false, Onerror=none): "" "recursively delete a directory tree. If ignore_errors is set, errors is ignored; Otherwise, if OnError is set, it's called to handle the error with arguments (func, Path, Exc_info) where Func is O    S.listdir, Os.remove, or os.rmdir; Path is the argument to, that function, caused it to fail;  And Exc_info is a tuple returned by Sys.exc_info ().    If Ignore_errors is false and onerror are None, an exception is raised.            "" "If Ignore_errors:def onerror (*args): Pass elif onerror is None:def onerror (*args):            Raise Try:if Os.path.islink (path): # symlinks to directories is forbidden, see bug #1669 Raise OSError ("Cannot call Rmtree on a symbolic link") except Oserror:onerror (Os.path.islink, PATH, s Ys.exc_info ()) # can ' t continue even if onerror hook returns return names = [] try:names = OS. Listdir (PATH)    Except Os.error, Err:onerror (os.listdir, Path, Sys.exc_info ()) for name in Names:fullname = Os.path        . Join (path, name) Try:mode = Os.lstat (fullname). St_mode except Os.error:mode = 0 If Stat. S_isdir (Mode): Rmtree (FullName, Ignore_errors, onerror) Else:try:os.remove (f Ullname) except Os.error, Err:onerror (Os.remove, FullName, Sys.exc_info ()) try:os.rm   Dir (path) except Os.error:onerror (Os.rmdir, Path, Sys.exc_info ())

Move

Shutil.move (SRC, DST)
To move a file recursively

def move (SRC, DST): "" "recursively move a file or directory to another location.    This was similar to the Unix "MV" command. 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 are not a directory, it could be overwritten depending on os.rename () semantics.    If the destination is on the filesystem and then rename () is used.    Otherwise, SRC is copied to the destination and then removed.  A lot more could is 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 insensit            ive filesystem, # perform the rename anyway. Os.rename (SRC, DST) return REAL_DST = Os.path.join (DST, _basename (SRC)) if os.path.exists (Real_ds T): RaisE Error, "Destination path '%s ' already exists"% real_dst try:os.rename (SRC, real_dst) except OSError: If Os.path.isdir (SRC): If _DESTINSRC (SRC, DST): Raise Error, "Cannot move a directory '%s ' in            To itself '%s '. "% (src, DST) copytree (SRC, REAL_DST, symlinks=true) rmtree (SRC) Else:   Copy2 (SRC, real_dst) os.unlink (SRC)

Make_archive

Shutil.make_archive (base_name, Format,...)

Create a compressed package and return the file path, for example: Zip, tar

      • base_name: The file name of the compressed package, or the path to the compressed package. When the file name is only, save to the current directory, otherwise save to the specified path,

      • format: Compressed package type, "Zip", "tar", "Bztar", "Gztar"
      • root_dir: Folder path to compress (default current directory)
      • owner: User, default current user
      • group: Group, default current group
      • logger: Used for logging, usually logging. Logger object
#将/users/wupeiqi/downloads/test file package to place the current program directory Import Shutilret = shutil.make_archive ("wwwwwwwwww", ' Gztar ', Root_dir = '/users/wupeiqi/downloads/test ')  #将/users/wupeiqi/downloads/test file Package Placement/users/wupeiqi/Directory Import Shutilret = Shutil.make_archive ("/users/wupeiqi/wwwwwwwwww", ' Gztar ', root_dir= '/users/wupeiqi/downloads/test ')

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'll 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 ' is 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 ' is 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 are 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:form    At_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[' ow        Ner '] = owner kwargs[' group '] = Group Try:filename = func (Base_name, Base_dir, **kwargs) finally: If Root_dir is not none:if logger are not None:logger.debug ("Changing Back to '%s '", Save_c   WD) Os.chdir (SAVE_CWD) return filename

Shutil Processing of compressed packets is done by calling the ZipFile and Tarfile two modules, in detail:

Import zipfile# Compression z = zipfile. ZipFile (' Laxi.zip ', ' W ') z.write (' A.log ') z.write (' Data.data ') Z.close () # Unzip z = zipfile. ZipFile (' Laxi.zip ', ' R ') Z.extractall () z.close () ZipFile compression decompression

Import tarfile# Compressed tar = Tarfile.open (' Your.tar ', ' W ') tar.add ('/users/wupeiqi/pycharmprojects/bbs2.zip ', arcname= ' Bbs2.zip ') tar.add ('/users/wupeiqi/pycharmprojects/cmdb.zip ', arcname= ' Cmdb.zip ') Tar.close () # Unzip tar = Tarfile.open ( ' Your.tar ', ' R ') Tar.extractall ()  # can set decompression address tar.close () Tarfile compression decompression

Python Shutil Module

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.