Python文件系統——shutil

6.5 shutil———高級文件操做

高級文件操做,如複製和設置文件權限

6.5.1 複製文件
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)
        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)
默認行爲是使用大數據塊讀取。使用-1會一次性讀取全部輸入,或者使用其餘正數能夠設置特定塊的大小。
>>> ================================ 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()函數會用一樣的方式解釋輸出名。若是指定的目標指示一個目錄而不是一個文件,會使用源文件的基名在該目錄中建立一個新文件。
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()工做相似copy(),不過複製到新文件的元數據會包含訪問和修改時間。
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
    
6.5.2 複製文件元數據
在UNIX建立一個新文件,會根據當前用戶的umask接授權限。要把權限從一個文件複製到另外一個文件,可使用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')
要複製其餘元數據,可使用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()只會複製與文件關聯的權限和日期。

6.5.3 處理目錄樹
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 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相似。若是源與目標都在同一個文件系統內,則會重命名源文件。不然,源文件會複製到目標文件,將源文件刪除。

>>> ================================ RESTART ================================
>>> 
BEFORE:  ['example', 'example.txt']
AFTER:  ['example', 'example.out']
相關文章
相關標籤/搜索