Python的shutil模塊中文件的復(fù)制操作函數(shù)詳解
copy()
chutil.copy(source, destination)
shutil.copy() 函數(shù)實(shí)現(xiàn)文件復(fù)制功能,將 source 文件復(fù)制到 destination 文件夾中,兩個(gè)參數(shù)都是字符串格式。如果 destination 是一個(gè)文件名稱,那么它會(huì)被用來當(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.*')
這個(gè)函數(shù)會(huì)打開輸入文件進(jìn)行讀寫,而不論其類型,所以某些特殊文件不可以用copyfile()復(fù)制為新的特殊文件。
>>> ================================ RESTART ================================ >>> BEFORE: ['huanhuan.txt'] AFTER: ['huanhuan.txt', 'huanhuan.txt.copy']
copyfile()實(shí)際是使用了底層函數(shù)copyfileobj()。copyfile()的參數(shù)是文件名,copyfileobj()的參數(shù)是打開的文件句柄。第三個(gè)參數(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會(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
類似于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()工作類似copy(),不過復(fù)制到新文件的元數(shù)據(jù)會(huì)包含訪問和修改時(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)前用戶的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)限和日期。
處理目錄樹
shutil包含三個(gè)函數(shù)處理目錄樹。要把一個(gè)目錄從一個(gè)位置復(fù)制到另一個(gè)位置,使用copytree()。這會(huì)遞歸遍歷源目錄樹,將文件復(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*')
其語義與UNIX命令mv類似。如果源與目標(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)一個(gè)簡單的圖床功能
在網(wǎng)上分享圖片或?qū)D片嵌入到網(wǎng)頁中時(shí),通常需要一個(gè)圖床來存儲(chǔ)和管理這些圖片,所以本文就來為大家介紹一下如何使用Python輕松實(shí)現(xiàn)一個(gè)簡單的圖床功能吧2024-01-01
Python解析json之ValueError: Expecting property name enclosed in
這篇文章主要給大家介紹了關(guān)于Python解析json報(bào)錯(cuò):ValueError: Expecting property name enclosed in double quotes: line 1 column 2(char 1)的解決方法,文中介紹的非常詳細(xì),需要的朋友們可以參考借鑒,下面來一起看看吧。2017-07-07
pandas DataFrame索引行列的實(shí)現(xiàn)
這篇文章主要介紹了pandas DataFrame索引行列的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-06-06
python利用opencv實(shí)現(xiàn)顏色檢測(cè)
這篇文章主要為大家詳細(xì)介紹了python利用opencv實(shí)現(xiàn)顏色檢測(cè),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-02-02
python中dot函數(shù)運(yùn)算過程總結(jié)
dot函數(shù)為numpy庫下的一個(gè)函數(shù),主要用于矩陣的乘法運(yùn)算,其中包括:向量內(nèi)積、多維矩陣乘法和矩陣與向量的乘法,下面這篇文章主要給大家介紹了關(guān)于python中dot函數(shù)運(yùn)算過程的相關(guān)資料,需要的朋友可以參考下2022-09-09

