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 globprint '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 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)
默認行為是使用大數據塊讀取。使用-1會一次性讀取所有輸入,或者使用其他正數可以設置特定塊的大小。
>>> ================================ RESTART ================================>>> Defalut:read(16384) bytesread(16384) bytesAll at once:read(-1) bytesread(-1) bytesBlocks of 256:read(256) bytesread(256) bytesread(256) bytes
類似于UNIX命令行工具cp,copy()函數會用同樣的方式解釋輸出名。如果指定的目標指示一個目錄而不是一個文件,會使用源文件的基名在該目錄中創建一個新文件。
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()工作類似copy(),不過復制到新文件的元數據會包含訪問和修改時間。
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)文件特性和原文件完全相同。
>>> ================================ 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
復制文件元數據
在UNIX創建一個新文件,會根據當前用戶的umask接受權限。要把權限從一個文件復制到另一個文件,可以使用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')要復制其他元數據,可以使用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')使用copystat()只會復制與文件關聯的權限和日期。
處理目錄樹
shutil包含三個函數處理目錄樹。要把一個目錄從一個位置復制到另一個位置,使用copytree()。這會遞歸遍歷源目錄樹,將文件復制到目標。
copytree()可以將當前這個實現當作起點,在使用前要讓它更健壯,可以增加一些特性,如進度條。
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')symlinks參數控制著符號鏈接作為鏈接復制還是文件復制。默認將內容復制到新文件,如果選項為true,會在目標中創建新的符號鏈接。
要刪除一個目錄及其內容,可以使用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')將一個文件或目錄從一個位置移動到另一個位置,可以使用move()。
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*')其語義與UNIX命令mv類似。如果源與目標都在同一個文件系統內,則會重命名源文件。否則,源文件會復制到目標文件,將源文件刪除。
>>> ================================ RESTART ================================>>> BEFORE: ['example', 'example.txt']AFTER: ['example', 'example.out']
新聞熱點
疑難解答
圖片精選