Python 中 Shutil 模塊詳情
一、什么是shutil
shutil可以簡單地理解為sh + util ,shell工具的意思。shutil模塊是對os模塊的補充,主要針對文件的拷貝、刪除、移動、壓縮和解壓操作。
二、shutil模塊的主要方法
1. shutil.copyfileobj(fsrc, fdst[, length=16*1024])
copy文件內(nèi)容到另一個文件,可以copy指定大小的內(nèi)容。這個方法是shutil模塊中其它拷貝方法的基礎,其它方法在本質上都是調用這個方法。
讓我們看一下它的源碼:
def copyfileobj(fsrc, fdst, length=16*1024):
while 1:
buf = fsrc.read(length)
if not buf:
break
fdst.write(buf)
代碼很簡單,一看就懂。但是要注意,其中的fsrc,fdst都是使用open()方法打開后的文件對象。
import shutil
s =open('fsrc.txt','r')
d=open('fdst.txt','w')
shutil.copyfileobj(s,d,length=16*1024)
2. shutil.copyfile(src, dst)
拷貝文件:
shutil.copyfile('f1.log', 'f2.log') #目標文件無需存在
3. shutil.copymode(src, dst)
僅拷貝權限。內(nèi)容、組、用戶均不變
shutil.copymode('f1.log', 'f2.log') #目標文件必須存在
4. shutil.copystat(src, dst)
僅拷貝狀態(tài)的信息,包括:mode bits, atime, mtime, flags
shutil.copystat('f1.log', 'f2.log') #目標文件必須存在
5. shutil.copy(src, dst)
拷貝文件和權限
import shutil
shutil.copy('f1.log', 'f2.log')
6. shutil.copy2(src, dst)
拷貝文件和狀態(tài)信息
import shutil
shutil.copy2('f1.log', 'f2.log')
7. shutil.copytree(src, dst, symlinks=False, ignore=None)
遞歸的去拷貝文件夾
src:源文件夾dst:復制至dst文件夾,該文件夾會自動創(chuàng)建,需保證此文件夾不存在,否則將報錯symlinks:是否復制軟連接,True復制軟連接,False不復制,軟連接會被當成文件復制過來,默認Falseignore:忽略模式,可傳入ignore_patterns()copy_function:拷貝文件的方式,可以傳入一個可執(zhí)行的處理函數(shù),默認為copy2,Python3新增參數(shù)ignore_dangling_symlinks:sysmlinks設置為False時,拷貝指向文件已刪除的軟連接時,將會報錯,如果想消除這個異常,可以設置此值為True。默認為False,Python3新增參數(shù)。
import shutil,os
folder1 = os.path.join(os.getcwd(),"aaa")
# bbb與ccc文件夾都可以不存在,會自動創(chuàng)建
folder2 = os.path.join(os.getcwd(),"bbb","ccc")
# 將"abc.txt","bcd.txt"忽略,不復制
shutil.copytree(folder1,folder2,ignore=shutil.ignore_patterns("abc.txt","bcd.txt"))

8. shutil.rmtree(path[, ignore_errors[, onerror]])
遞歸的去刪除文件
import shutil
shutil.rmtree('folder1')
9. shutil.move(src, dst)
遞歸的去移動文件,它類似mv命令,其實就是重命名。
import shutil
shutil.move('folder1', 'folder3')
10.shutil.make_archive
(base_name, format[, root_dir[, base_dir, verbose, dry_run, owner, group, logger])
創(chuàng)建壓縮包并返回文件路徑,例如:zip、tar
創(chuàng)建壓縮包并返回文件路徑,例如:zip、tar
base_name:壓縮包的文件名,也可以是壓縮包的路徑。只是文件名時,則保存至當前目錄,否則保存至指定路徑,
- 如
data_bak保存至當前路徑 。 - 如:/tmp/data_bak =>保存至/tmp/
format:壓縮包種類,“zip”, “tar”, “bztar”,“gztar”
root_dir:要壓縮的文件夾路徑(默認當前目錄)
owner:用戶,默認當前用戶
group:組,默認當前組
logger:用于記錄日志,通常是logging.Logger對象
把當前目錄下的文件壓縮生成copy.zip文件到當前目錄下注意:此操作會出現(xiàn)遞歸拷貝壓縮導致文件損壞(當前目錄下的copy.zip中會有copy.zip)
import shutil
shutil.make_archives('D:\copy3\copy','zip',base_dir='D:\copy2\\測試.txt')
把D:\copy2\測試.txt文件壓縮,在D:\copy3\路徑下生成copy.zip。
import shutil
shutil.make_archives('copy','zip')

三、總結
到此這篇關于 Python 中 Shutil 模塊詳情的文章就介紹到這了,更多相關 Python 中 Shutil 模塊內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
python爬蟲實現(xiàn)POST request payload形式的請求
這篇文章主要介紹了python爬蟲實現(xiàn)POST request payload形式的請求,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-04-04
Python實現(xiàn)查找最小的k個數(shù)示例【兩種解法】
這篇文章主要介紹了Python實現(xiàn)查找最小的k個數(shù),結合實例形式對比分析了Python常見的兩種列表排序、查找相關操作技巧,需要的朋友可以參考下2019-01-01

