The copy operation function of the file in the Python shutil module is detailed _python

Source: Internet
Author: User
Tags chmod file copy glob mkdir print print string format

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 is equal to 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 in the string format after the successful copy.

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

From shutil Import *
glob import glob
print ' 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 as new special files with CopyFile ().

>>> ================================ Restart ================================
>>> 
Before: [' Huanhuan.txt '] after
: [' huanhuan.txt ', ' huanhuan.txt.copy ']

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

 shutil import * Import os from Stringio import stringio import sys class Verbosestrin GIO (Stringio): def read (self, n=-1): next = Stringio.read (self, n) print ' read (%d) bytes '% n return next lo Rem_ipsum = "' This makes the dependency explicit, limits the scope to the" current file and provides faster access to the "
bit.* functions, too. It ' s good programming practice not to rely on the global variable bit being set assuming some
Ion has already loaded the module). The Require function ensures the "module is" only loaded once. ' Print ' defalut: ' input = Verbosestringio (lore m_ipsum) output = Stringio () copyfileobj (input, output) print print ' All at once: ' input = Verbosestringio (lorem_ipsum) ou Tput = Stringio () copyfileobj (input, output,-1) Print print ' Blocks of 256: ' input = Verbosestringio (lorem_ipsum) output = Stringio () copyfileobj (input, output, 256) 

The default behavior is to read with large blocks of data. Using-1 will read all input at once, or you can use other positive numbers to set the size of a particular block.

>>> ================================ Restart ================================
>>> 
Defalut:
Read (16384) bytes
Read (16384) bytes all at

once:
read ( -1) bytes
Read ( -1) bytes

Blocks of 256:
read (256) bytes
read (256) bytes
read (256) bytes

Similar to the Unix command-line tool Cp,copy () function 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 os
dir = 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 copied to the new file contains the access and modification time.

From shutil Import *
import OS
import time
dir = os.getcwd ()
If not os.path.exists ('%s\\example '% dir): C6/>os.mkdir ('%s\\example '% 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 Feb 17:42:46 2014
  accessed:thu
  Feb-17:42:46 2014 modified:t Hu Feb 17:42:46 2014
DEST:
  Mode  : 33206 created:thu
  Feb 18:29:14 2014 Accessed:thu Feb
  13 17:42:46 2014
  Modified:thu Feb 13 17:42:46 2014

Copying file meta data
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 os out
commands import *
with open (' file_to_change.txt ', ' wt ') as F:
  F.W Rite (' I Love You ')
os.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 replicate other metadata, you can use Copystat ().

From shutil Import *
import OS
import time
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 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 () only copies the permissions and dates associated with the file.


working with a directory tree
the shutil contains three functions to work with 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 some features, such as a progress bar.

From shutil Import *
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 copy. By default, the content is copied to the 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 *
commands import *
print ' before: '
print getoutput (' ls-rlast/tmp/example ')
rmtree ('/tmp/example ')
print ' \nafter: '
print getoutput (' ls-rlast/tmp/example ')

Moving a file or directory from one location to another can use Move ().

From shutil import * "
glob import glob
with open" (' example.txt ', ' wt ') as F:
  f.write (' I Love you ')
print ' Before: ', Glob (' example* ') move
(' example.txt ', ' example.out ')
print ' After: ', Glob (' example* ')

The semantics are similar to the UNIX command mv. If the source and destination are in 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.