Python的shutil模塊中文件的復(fù)制操作函數(shù)詳解
copy()
chutil.copy(source, destination)
shutil.copy() 函數(shù)實(shí)現(xiàn)文件復(fù)制功能,將 source 文件復(fù)制到 destination 文件夾中,兩個(gè)參數(shù)都是字符串格式。如果 destination 是一個(gè)文件名稱(chēng),那么它會(huì)被用來(lái)當(dāng)作復(fù)制后的文件名稱(chēng),即等于 復(fù)制 + 重命名。舉例如下:
>> 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'
如代碼所示,該函數(shù)的返回值是復(fù)制成功后的字符串格式的文件路徑。
copyfile()
copyfile()將源的內(nèi)容復(fù)制給目標(biāo),如果沒(méi)有權(quán)限寫(xiě)目標(biāo)文件則產(chǎn)生IoError
from shutil import * from glob import glob print 'BEFORE:', glob('huanhuan.*') copyfile('huanhuan.txt', 'huanhuan.txt.copy') print 'AFTER:', glob('huanhuan.*')
這個(gè)函數(shù)會(huì)打開(kāi)輸入文件進(jìn)行讀寫(xiě),而不論其類(lèi)型,所以某些特殊文件不可以用copyfile()復(fù)制為新的特殊文件。
>>> ================================ RESTART ================================ >>> BEFORE: ['huanhuan.txt'] AFTER: ['huanhuan.txt', 'huanhuan.txt.copy']
copyfile()實(shí)際是使用了底層函數(shù)copyfileobj()。copyfile()的參數(shù)是文件名,copyfileobj()的參數(shù)是打開(kāi)的文件句柄。第三個(gè)參數(shù)可選,用于讀入塊的緩沖區(qū)長(zhǎng)度。
from shutil import * import os from StringIO import StringIO import sys class VerboseStringIO(StringIO): def read(self, n=-1): next = StringIO.read(self, n) print 'read(%d) bytes' % n return next lorem_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) print print 'All at once:' input = VerboseStringIO(lorem_ipsum) output = StringIO() copyfileobj(input, output, -1) print print 'Blocks of 256:' input = VerboseStringIO(lorem_ipsum) output = StringIO() copyfileobj(input, output, 256)
默認(rèn)行為是使用大數(shù)據(jù)塊讀取。使用-1會(huì)一次性讀取所有輸入,或者使用其他正數(shù)可以設(shè)置特定塊的大小。
>>> ================================ 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
類(lèi)似于UNIX命令行工具cp,copy()函數(shù)會(huì)用同樣的方式解釋輸出名。如果指定的目標(biāo)指示一個(gè)目錄而不是一個(gè)文件,會(huì)使用源文件的基名在該目錄中創(chuàng)建一個(gè)新文件。
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()工作類(lèi)似copy(),不過(guò)復(fù)制到新文件的元數(shù)據(jù)會(huì)包含訪問(wèn)和修改時(shí)間。
from shutil import * import os import time dir = 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 2014 DEST: 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
復(fù)制文件元數(shù)據(jù)
在UNIX創(chuàng)建一個(gè)新文件,會(huì)根據(jù)當(dāng)前用戶(hù)的umask接受權(quán)限。要把權(quán)限從一個(gè)文件復(fù)制到另一個(gè)文件,可以使用copymode()。
from shutil import * import os from 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')
要復(fù)制其他元數(shù)據(jù),可以使用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')
使用copystat()只會(huì)復(fù)制與文件關(guān)聯(lián)的權(quán)限和日期。
處理目錄樹(shù)
shutil包含三個(gè)函數(shù)處理目錄樹(shù)。要把一個(gè)目錄從一個(gè)位置復(fù)制到另一個(gè)位置,使用copytree()。這會(huì)遞歸遍歷源目錄樹(shù),將文件復(fù)制到目標(biāo)。
copytree()可以將當(dāng)前這個(gè)實(shí)現(xiàn)當(dāng)作起點(diǎn),在使用前要讓它更健壯,可以增加一些特性,如進(jìn)度條。
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參數(shù)控制著符號(hào)鏈接作為鏈接復(fù)制還是文件復(fù)制。默認(rèn)將內(nèi)容復(fù)制到新文件,如果選項(xiàng)為true,會(huì)在目標(biāo)中創(chuàng)建新的符號(hào)鏈接。
要?jiǎng)h除一個(gè)目錄及其內(nèi)容,可以使用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')
將一個(gè)文件或目錄從一個(gè)位置移動(dòng)到另一個(gè)位置,可以使用move()。
from shutil import * from 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*')
其語(yǔ)義與UNIX命令mv類(lèi)似。如果源與目標(biāo)都在同一個(gè)文件系統(tǒng)內(nèi),則會(huì)重命名源文件。否則,源文件會(huì)復(fù)制到目標(biāo)文件,將源文件刪除。
>>> ================================ RESTART ================================ >>> BEFORE: ['example', 'example.txt'] AFTER: ['example', 'example.out']
相關(guān)文章
淺談Python實(shí)現(xiàn)Apriori算法介紹
這篇文章主要介紹了淺談Python實(shí)現(xiàn)Apriori算法介紹,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-12-12從局部變量和全局變量開(kāi)始全面解析Python中變量的作用域
無(wú)論是以類(lèi)為基礎(chǔ)的面相對(duì)象編程,還是單純函數(shù)內(nèi)部變量的定義,變量的作用域始終是Python學(xué)習(xí)中一個(gè)必須理解掌握的環(huán)節(jié),下面我們從局部變量和全局變量開(kāi)始全面解析Python中變量的作用域,需要的朋友可以參考下2016-06-06PyTorch中view()與?reshape()的區(qū)別詳析
這篇文章主要給大家介紹了關(guān)于PyTorch中view()?與?reshape()?區(qū)別的相關(guān)資料,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2022-01-01python實(shí)現(xiàn)多層感知器MLP(基于雙月數(shù)據(jù)集)
這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)多層感知器MLP,基于雙月數(shù)據(jù)集,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-01-01Python名片管理系統(tǒng)+猜拳小游戲案例實(shí)現(xiàn)彩(色控制臺(tái)版)
這篇文章主要介紹了Python名片管理系統(tǒng)+猜拳小游戲案例實(shí)現(xiàn)彩(色控制臺(tái)版),文章圍繞主題展開(kāi)詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,感興趣的小伙伴可以參考一下2022-08-08Python Pillow.Image 圖像保存和參數(shù)選擇方式
今天小編就為大家分享一篇Python Pillow.Image 圖像保存和參數(shù)選擇方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-01-01python實(shí)現(xiàn)植物大戰(zhàn)僵尸游戲?qū)嵗a
這篇文章主要給大家介紹了關(guān)于python實(shí)現(xiàn)植物大戰(zhàn)僵尸游戲的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用python具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-06-06