Python的shutil模塊中文件的復(fù)制操作函數(shù)詳解
copy()
chutil.copy(source, destination)
shutil.copy() 函數(shù)實現(xiàn)文件復(fù)制功能,將 source 文件復(fù)制到 destination 文件夾中,兩個參數(shù)都是字符串格式。如果 destination 是一個文件名稱,那么它會被用來當(dāng)作復(fù)制后的文件名稱,即等于 復(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),如果沒有權(quán)限寫目標(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.*')
這個函數(shù)會打開輸入文件進行讀寫,而不論其類型,所以某些特殊文件不可以用copyfile()復(fù)制為新的特殊文件。
>>> ================================ RESTART ================================ >>> BEFORE: ['huanhuan.txt'] AFTER: ['huanhuan.txt', 'huanhuan.txt.copy']
copyfile()實際是使用了底層函數(shù)copyfileobj()。copyfile()的參數(shù)是文件名,copyfileobj()的參數(shù)是打開的文件句柄。第三個參數(shù)可選,用于讀入塊的緩沖區(qū)長度。
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會一次性讀取所有輸入,或者使用其他正數(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
類似于UNIX命令行工具cp,copy()函數(shù)會用同樣的方式解釋輸出名。如果指定的目標(biāo)指示一個目錄而不是一個文件,會使用源文件的基名在該目錄中創(chuàng)建一個新文件。
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()工作類似copy(),不過復(fù)制到新文件的元數(shù)據(jù)會包含訪問和修改時間。
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)建一個新文件,會根據(jù)當(dāng)前用戶的umask接受權(quán)限。要把權(quán)限從一個文件復(fù)制到另一個文件,可以使用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()只會復(fù)制與文件關(guān)聯(lián)的權(quán)限和日期。
處理目錄樹
shutil包含三個函數(shù)處理目錄樹。要把一個目錄從一個位置復(fù)制到另一個位置,使用copytree()。這會遞歸遍歷源目錄樹,將文件復(fù)制到目標(biāo)。
copytree()可以將當(dāng)前這個實現(xiàn)當(dāng)作起點,在使用前要讓它更健壯,可以增加一些特性,如進度條。
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ù)控制著符號鏈接作為鏈接復(fù)制還是文件復(fù)制。默認(rèn)將內(nèi)容復(fù)制到新文件,如果選項為true,會在目標(biāo)中創(chuàng)建新的符號鏈接。
要刪除一個目錄及其內(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')
將一個文件或目錄從一個位置移動到另一個位置,可以使用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*')
其語義與UNIX命令mv類似。如果源與目標(biāo)都在同一個文件系統(tǒng)內(nèi),則會重命名源文件。否則,源文件會復(fù)制到目標(biāo)文件,將源文件刪除。
>>> ================================ RESTART ================================ >>> BEFORE: ['example', 'example.txt'] AFTER: ['example', 'example.out']
相關(guān)文章
PyTorch中view()與?reshape()的區(qū)別詳析
這篇文章主要給大家介紹了關(guān)于PyTorch中view()?與?reshape()?區(qū)別的相關(guān)資料,文中通過實例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2022-01-01
python實現(xiàn)多層感知器MLP(基于雙月數(shù)據(jù)集)
這篇文章主要為大家詳細介紹了python實現(xiàn)多層感知器MLP,基于雙月數(shù)據(jù)集,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-01-01
Python名片管理系統(tǒng)+猜拳小游戲案例實現(xiàn)彩(色控制臺版)
這篇文章主要介紹了Python名片管理系統(tǒng)+猜拳小游戲案例實現(xiàn)彩(色控制臺版),文章圍繞主題展開詳細的內(nèi)容介紹,具有一定的參考價值,感興趣的小伙伴可以參考一下2022-08-08
Python Pillow.Image 圖像保存和參數(shù)選擇方式
今天小編就為大家分享一篇Python Pillow.Image 圖像保存和參數(shù)選擇方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-01-01
python實現(xiàn)植物大戰(zhàn)僵尸游戲?qū)嵗a
這篇文章主要給大家介紹了關(guān)于python實現(xiàn)植物大戰(zhàn)僵尸游戲的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家學(xué)習(xí)或者使用python具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2019-06-06

