Python module introduction-shutil advanced file operations

Source: Internet
Author: User
Tags glob

Introduction

The shutil module provides advanced operations for a large number of files. Especially for file copying and deletion, the main functions are directory and file operations and compression operations. For operations on a single file, see the OS module.

Note that even higher-level file replication functions (shutil. copy (), shutil. copy2 () cannot copy the metadata of all files. This means that on the POSIX platform, the file owner, group, and access control list will be lost. In Mac OS, resource fork and other metadata cannot be used. This means that resources will be lost, and the file type and creator code will be incorrect. On Windows, the file owner, ACL, and backup data streams are not copied.

    Function: Advanced file operations. Type: standard module modules: OS standard modules. Zipfile standard module. Standard tarfile module. Copy an object

    Shutil. copyfile (src, dst): copy the file content (excluding metadata) from src to dst. DST must be the complete target file name. For the copy directory, see shutil. copy (). If src and dst are the same file, an Error shutil. Error is thrown. Dst must be writable; otherwise, an IOError occurs. If dst already exists, it will be replaced. This feature is not available for special files, such as characters, Block devices, and pipelines, because copyfile will open and read files. Src and dst are path names in string format.

    from shutil import *from glob import globprint 'BEFORE:', glob('shutil_copyfile.*')copyfile('shutil_copyfile.py', 'shutil_copyfile.py.copy')print 'AFTER:', glob('shutil_copyfile.*')

    Execution result:

    # python shutil_copyfile.pyBEFORE: ['shutil_copyfile.py']AFTER: ['shutil_copyfile.py', 'shutil_copyfile.py.copy']# python shutil_copyfile.pyBEFORE: ['shutil_copyfile.py', 'shutil_copyfile.py.copy']

    Copyfile () calls the base function layer copyfileobj ().
    Shutil. copyfileobj (fsrc, fdst [, length]): copy the file content (excluding metadata) from the class file object src to the class file to dst. The optional parameter length specifies the buffer size. A negative value indicates one-time reading. By default, data is split into small copies to avoid occupying too much memory. Note: The copy operation starts from the current fsrc file.

    from shutil import *import osfrom StringIO import StringIOimport sysclass VerboseStringIO(StringIO):    def read(self, n=-1):        next = StringIO.read(self, n)        print 'read(%d) bytes' % n        return nextlorem_ipsum = '''Lorem ipsum dolor sit amet, consectetuer adipiscingelit.  Vestibulum aliquam mollis dolor. Donec vulputate nunc ut diam.Ut rutrum mi vel sem. Vestibulum ante ipsum.'''print 'Default:'input = VerboseStringIO(lorem_ipsum)output = StringIO()copyfileobj(input, output)printprint 'All at once:'input = VerboseStringIO(lorem_ipsum)output = StringIO()copyfileobj(input, output, -1)printprint 'Blocks of 256:'input = VerboseStringIO(lorem_ipsum)output = StringIO()copyfileobj(input, output, 256)

    Execution result:

    # python shutil_copyfileobj.pyDefault:read(16384) bytesread(16384) bytesAll at once:read(-1) bytesread(-1) bytesBlocks of 256:read(256) bytesread(256) bytes

    Shutil. copy (src, dst): copy the src file to the file or directory dst. If dst is a directory, use the same src file name to create (or overwrite), the permission bit will also be copied. Src and dst are path names in string format.

    from shutil import *import osos.mkdir('example')print 'BEFORE:', os.listdir('example')copy('shutil_copy.py', 'example')print 'AFTER:', os.listdir('example')

    Execution result:

    # python shutil_copy.pyBEFORE: []AFTER: ['shutil_copy.py'

    Shutil. copy2 (src, dst): similar to shutil. copy, metadata is also copied. In fact, shutil. copy is called first, and copystat is used. This is similar to the Unix Command cp-p.

    from shutil import *import osimport timedef show_file_info(filename):    stat_info = os.stat(filename)    print '\tMode    :', stat_info.st_mode    print '\tCreated :', time.ctime(stat_info.st_ctime)    print '\tAccessed:', time.ctime(stat_info.st_atime)    print '\tModified:', time.ctime(stat_info.st_mtime)os.mkdir('example')print 'SOURCE:'show_file_info('shutil_copy2.py')copy2('shutil_copy2.py', 'example')print 'DEST:'show_file_info('example/shutil_copy2.py')

    Execution result:

    # python shutil_copy2.pySOURCE:        Mode    : 33279        Created : Fri Dec  6 10:45:52 2013        Accessed: Fri Dec  6 11:49:40 2013        Modified: Mon Feb 21 01:37:46 2011DEST:        Mode    : 33279        Created : Fri Dec  6 11:51:58 2013        Accessed: Fri Dec  6 11:49:40 2013        Modified: Mon Feb 21 01:37:46 2011

    Shutil. ignore_patterns (* patterns) is an auxiliary function of copytree and provides the glob function, for example:

    from shutil import copytree, ignore_patternscopytree(source, destination, ignore=ignore_patterns('*.pyc', 'tmp*'))
    Copy object metadata
    Delete the following parts. For more information, see the following link.
    Compression and decompression
    Delete the following parts. For more information, see the following link.
    Address of this Article
      Http://automationtesting.sinaapp.com/blog/m_shutilreference Material
        Http://docs.python.org/2/library/shutil.html? Http://zh.wikipedia.org/wiki/Base64? Http://pymotw.com/2/shutil? Http://effbot.org/librarybook/shutil.htm

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.