A detailed description of the copy operation function of the file in the Python shutil module

Source: Internet
Author: User
Tags file copy glob
Copy ()
Chutil.copy (source, destination)
The Shutil.copy () function implements the file copy function, copying the source file into the destination folder, and two parameters are in string format. If destination is a file name, it is used as the copied file name, which equals copy + rename. Examples are as follows:

>> Import shutil >> import os >> os.chdir (' c:\\ ') >> shutil.copy (' c:\\spam.txt ', ' c:\\delicious ' ) ' C:\\delicious\\spam.txt ' >> shutil.copy (' eggs.txt ', ' c:\\delicious\\eggs2.txt ') ' C:\\delicious\\eggs2.txt '

As the code shows, the return value of the function is the file path of the string format after the successful copy.

CopyFile ()
CopyFile () copies the contents of the source to the target and generates IOERROR if no permission is written to the target file

From shutil import *from glob import Globprint ' before: ', Glob (' huanhuan.* ') copyfile (' Huanhuan.txt ', ' huanhuan.txt.copy ') print ' after: ', Glob (' huanhuan.* ')

This function opens the input file for reading and writing, regardless of its type, so some special files cannot be copied to the new special file with CopyFile ().

>>> ================================ RESTART ================================>>> BEFORE: [' Huanhuan.txt ']after: [' huanhuan.txt ', ' huanhuan.txt.copy ']

CopyFile () is actually using the underlying function copyfileobj (). The argument to CopyFile () is the file name, and the argument to Copyfileobj () is a handle to the open document. The third parameter is optional and is used to read the buffer length of a block.

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 = "This makes Ndency explicit, limits the scope to the current file and provides faster access to the bit.* functions, too. It's good programming practice rely on the global variable bit being set (assuming some other part of your applicat Ion has already loaded the module). The Require function ensures the module is a loaded once, in any case. print ' defalut: ' 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)

The default behavior is to use large chunks of data to read. Use 1 to read all inputs at once, or use other positive numbers to set the size of a particular block.

>>> ================================ RESTART ================================>>> Defalut:read ( 16384) bytesread (16384) Bytesall at Once:read ( -1) bytesread ( -1) Bytesblocks of 256:read (+) Bytesread (+) Bytesread ( bytes)

The Cp,copy () function, similar to the UNIX command-line tool, interprets the output name in the same way. If the specified target indicates a directory instead of a file, a new file is created in the directory using the base name of the source file.

From shutil import *import osdir = OS.GETCWD () if not os.path.exists ('%s\\example '% dir):  os.mkdir ('%s\\example '% dir print ' Before: ', Os.listdir (' example ') copy (' Huanhuan.txt ', ' example ') print ' after: ', Os.listdir (' example ')

>>> ================================ RESTART ================================>>> BEFORE: []AFTER: [' Huanhuan.txt ']

Copy2 ()

Copy2 () works like copy (), but the metadata that is copied to the new file contains the access and modification times.

From shutil import *import osimport timedir = OS.GETCWD () if not os.path.exists ('%s\\example '% dir):  os.mkdir ('%s\\ex Ample '% dir)  def 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) print ' SOURCE: ' Show_file_info (' Huanhuan.txt ') copy2 (' Huanhuan.txt ', ' example ') print ' DEST: ' Show_file_info ('%s\\example\\huanhuan.txt '% dir)

The file attributes are exactly the same as the original file.

>>> ================================ RESTART ================================>>> SOURCE:  Mode  : 33206  created:thu 17:42:46  accessed:thu Feb 17:42:46 modified:thu  Feb 13 17 : 42:46 2014DEST:  Mode  : 33206  created:thu 18:29:14  accessed:thu  Dified:thu Feb 13 17:42:46 2014

Copying file metadata
Creating a new file on Unix will accept permissions based on the current user's umask. To copy permissions from one file to another, you can use Copymode ().

From shutil import *import osfrom commands import *with open (' file_to_change.txt ', ' wt ') as F:  f.write (' I Love you ') o S.chmod (' File_to_change.txt ', 0444) print ' Before: ' Print GetStatus (' File_to_change.txt ') copymode (' Shutil_ copymode.py ', ' file_to_change.txt ') print ' after: ' Print GetStatus (' file_to_change.txt ')

To copy additional metadata, you can use Copystat ().

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) with open (' File_to_change.txt ', ' wt ') as F:  f.write (' I Love You ') os.chmod (' File_to_change.txt ', 0444) print ' Before: ' Show_ File_info (' File_to_change.txt ') copystat (' shutil_copystat.py ', ' file_to_change.txt ') print ' after: ' Show_file_info ( ' File_to_change.txt ')

Using Copystat () copies only the permissions and dates associated with the file.


Working with the directory tree
Shutil contains three functions to handle the directory tree. To copy a directory from one location to another, use Copytree (). This recursively iterates through the source tree and copies the files to the destination.
Copytree () can take the current implementation as a starting point, make it more robust before use, and add features such as a progress bar.

From shutil import *from commands import *print ' before: ' Print getoutput (' ls-rlast/tmp/example ') copytree ('.. /shutil ', '/tmp/example ') print ' \nafter: ' Print getoutput (' ls-rlast/tmp/example ')

The Symlinks parameter controls whether the symbolic link is copied as a link or a file. By default, the content is copied to a new file, and if the option is true, a new symbolic link is created in the target.
To delete a directory and its contents, you can use Rmtree ().

From shutil import *from commands import *print ' before: ' Print getoutput (' ls-rlast/tmp/example ') rmtree ('/tmp/example ') print ' \nafter: ' Print getoutput (' ls-rlast/tmp/example ')

To move a file or directory from one location to another, you can use Move ().

From shutil import *from glob import Globwith open (' example.txt ', ' wt ') as F:  f.write (' I Love You ') print ' Before: ', g LOB (' example* ') Move (' Example.txt ', ' example.out ') print ' after: ', Glob (' example* ')

Its semantics are similar to the UNIX command mv. If the source and destination are within the same file system, the source file is renamed. Otherwise, the source file is copied to the destination file and the source file is deleted.

>>> ================================ RESTART ================================>>> BEFORE: [' Example ', ' Example.txt ']after: [' example ', ' example.out ']
  • 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.