copy()chutil.copy(source, destination)
shutil.copy() 函数实现文件复制功能,将 source 文件复制到 destination 文件夹中,两个参数都是字符串格式。如果 destination 是一个文件名称,那么它会被用来当作复制后的文件名称,即等于 复制 + 重命名。举例如下:
>> 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'
如代码所示,该函数的返回值是复制成功后的字符串格式的文件路径。
copyfile()copyfile()将源的内容复制给目标,如果没有权限写目标文件则产生IoError
from shutil import *
from glob import glob
print 'BEFORE:', glob('huanhuan.*')
copyfile('huanhuan.txt', 'huanhuan.txt.copy')
print 'AFTER:', glob('huanhuan.*')
这个函数会打开输入文件进行读写,而不论其类型,所以某些特殊文件不可以用copyfile()复制为新的特殊文件。
>>> ================================ RESTART ================================
>>>
BEFORE: ['huanhuan.txt']
AFTER: ['huanhuan.txt', 'huanhuan.txt.copy']
copyfile()实际是使用了底层函数copyfileobj()。copyfile()的参数是文件名,copyfileobj()的参数是打开的文件句柄。第三个参数可选,用于读入块的缓冲区长度。
from shutil import *
import os
from StringIO import StringIO
import sys
class VerboseStringIO(StringIO):
def read(self, n=-1):
next = StringIO.read(self, n)
<