Detailed description of the file copy operation function in the shutil module of Python,
Copy ()
Chutil. copy (source, destination)
The shutil. copy () function allows you to copy the source file to the destination folder. Both parameters are in string format. If destination is a file name, it is used as the name of the copied file, that is, copy + rename. Example:
>> 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 shown in the Code, the return value of this function is the file path in string format after successful copying.
Copyfile ()
Copyfile () copies the source content to the target. If you do not have the permission to write the target file, an IoError occurs.
from shutil import *from glob import globprint 'BEFORE:', glob('huanhuan.*')copyfile('huanhuan.txt', 'huanhuan.txt.copy')print 'AFTER:', glob('huanhuan.*')
This function will open the input file for read and write, regardless of its type, so some special files cannot be copied as new special files using copyfile.
>>> ================================ RESTART ================================>>> BEFORE: ['huanhuan.txt']AFTER: ['huanhuan.txt', 'huanhuan.txt.copy']
Copyfile () actually uses 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 and is used to read the buffer length of the 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 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 other part of your application has already loaded the module).The require function ensures the module is only 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 big data blocks for reading. If-1 is used, the system reads all input data at a time, or uses other positive numbers to set the size of a specific block.
>>> ================================ RESTART ================================>>> Defalut:read(16384) bytesread(16384) bytesAll at once:read(-1) bytesread(-1) bytesBlocks of 256:read(256) bytesread(256) bytesread(256) bytes
Similar to the UNIX command line tool cp, the copy () function interprets the output name in the same way. If the specified target indicates a directory rather than 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 copied to the new file contains the access and modification time.
from shutil import *import osimport timedir = os.getcwd()if not os.path.exists('%s\\example' % dir): 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 features are exactly the same as those of the original file.
>>> ================================ RESTART ================================>>> SOURCE: Mode : 33206 Created : Thu Feb 13 17:42:46 2014 Accessed: Thu Feb 13 17:42:46 2014 Modified: Thu Feb 13 17:42:46 2014DEST: Mode : 33206 Created : Thu Feb 13 18:29:14 2014 Accessed: Thu Feb 13 17:42:46 2014 Modified: Thu Feb 13 17:42:46 2014
Copy file metadata
When a new file is created in UNIX, the current user's umask will receive the permission. 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')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 copy other 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 () only copies the permissions and dates associated with the file.
Process directory tree
Shutil contains three function processing directory trees. To copy a directory from one location to another, use copytree (). This recursively traverses the source directory tree and copies the file to the target.
Copytree () can use the current implementation as the starting point. before using it, you must make it more robust and add some features, such as progress bars.
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 a symbolic link is used as a link copy or a file copy. By default, the content is copied to a new file. If the option is true, a new symbolic link is created in the target.
To delete a directory and its content, 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')
You can use move () to move a file or directory from one location to another ().
from shutil import *from glob import globwith open('example.txt', 'wt') as f: f.write('i love you')print 'BEFORE: ', glob('example*')move('example.txt', 'example.out')print 'AFTER: ',glob('example*')
Its syntax is similar to that of the UNIX Command mv. If both the source and target are in the same file system, the source file will be renamed. Otherwise, the source file will be copied to the target file and the source file will be deleted.
>>> ================================ RESTART ================================>>> BEFORE: ['example', 'example.txt']AFTER: ['example', 'example.out']