Python3 shutil(高級文件操作模塊)實例用法總結(jié)
1、shutil是shell
utility的縮寫
shutil.move直接從一個地方挪到另一個地方,而os.rename常常只能重命名,不能挪動位置。
功能是:
>>>shutil.move('old.txt',r'c:datarchive')
>>>shutil.copy('old.txt',r'c:datarchive')
>>>os.remove('junk.dat')
2、高級文件操作(拷貝/移動/壓縮/解壓縮)
#!/usr/bin/env python
# coding=utf-8
__author__ = 'zhuo'
__date__ = '2017/5/25'
# shutil_demo.py 高級文件操作(拷貝 / 移動 / 壓縮 / 解壓縮)
import shutil
def shutil_demo():
# 拷貝文件
shutil.copy2('file.txt', 'temp.txt')
# 拷貝目錄
shutil.copytree("root", "temp", symlinks=False, ignore=shutil.ignore_patterns("*.pyc"), copy_function=shutil.copy2, ignore_dangling_symlinks=True)
# 刪除目錄
shutil.rmtree("temp", ignore_errors=True)
# 移動文件/目錄
shutil.move("root", "temp", copy_function=shutil.copy2)
# 獲取磁盤使用空間
total, used, free = shutil.disk_usage(".")
print("當前磁盤共: %iGB, 已使用: %iGB, 剩余: %iGB"%(total / 1073741824, used / 1073741824, free / 1073741824))
# 壓縮文件
shutil.make_archive('Box', 'zip', 'temp')
# 解壓文件
shutil.unpack_archive('Box.zip')
def shutil_func():
# 文件和目錄操作
# shutil.copyfileobj(fsrc, fdst[, length]) // 拷貝文件內(nèi)容, 將fsrc文件里的內(nèi)容copy到fdst文件中, length:緩沖區(qū)大小
shutil.copyfileobj(open('file.txt', 'r'), open('temp.txt', 'w'))
# shutil.copyfile(src, dst, *, follow_symlinks=True) // 拷貝文件內(nèi)容, 同copyfileobj, 如果dst=src,拋SameFileError異常, dst存在則替換
dst = shutil.copyfile('file.txt', 'temp.txt')
# shutil.copymode(src, dst, *, follow_symlinks=True) // 僅拷貝權(quán)限, 其他信息不受影響
shutil.copymode('file.txt', 'temp.txt')
# shutil.copystat(src, dst, *, follow_symlinks=True) // 拷貝狀態(tài)(權(quán)限 / 最后訪問時間 / 上次修改時間 / 標志), 其他不受迎影響
shutil.copystat('file.txt', 'temp.txt')
# shutil.copy(src, dst, *, follow_symlinks=True) // 拷貝文件(數(shù)據(jù) / 權(quán)限)
dst = shutil.copy('file.txt', 'temp.txt')
# shutil.copy2(src, dst, *, follow_symlinks=True) // 拷貝文件(嘗試保留所有元數(shù)據(jù)) (不能拷貝創(chuàng)建時間,該時間可通過修改系統(tǒng)時間再創(chuàng)建文件來實現(xiàn))
dst = shutil.copy2('file.txt', 'temp.txt')
# shutil.ignore_patterns(*patterns)
# symlinks:True(復制鏈接) / False(復制文件), ignore=ignore_patterns("") // 忽略的文件, copy_function=自定義復制函數(shù), ignore_dangling_symlinks:True(忽略文件不存在異常) / False(錯誤列表中添加異常)
# shutil.copytree(src, dst, symlinks=False, ignore=None, copy_function=copy2, ignore_dangling_symlinks=False) // 遞歸的復制根目錄下的整個目錄樹
dst = shutil.copytree("root", "temp", symlinks=False, ignore=shutil.ignore_patterns("*.pyc"), copy_function=shutil.copy2, ignore_dangling_symlinks=True)
# shutil.rmtree(path, ignore_errors=False, onerror=None) // 刪除整個目錄樹, ignore_errors:是否忽略刪除失敗錯誤, onerror=def error(func, path, excinfo)
shutil.rmtree("temp", ignore_errors=True)
# shutil.move(src, dst, copy_function=copy2) // 遞歸移動文件/目錄, 目錄存在則移動目錄, 文件存在則覆蓋
dst = shutil.move("root", "temp", copy_function=shutil.copy2)
total, used, free = shutil.disk_usage(".") # 給定路徑的磁盤使用情況統(tǒng)計信息
# shutil.chown(path, user=None, group=None) // 修改用戶和組 (Unix可用)
# shutil.which(cmd, mode=os.F_OK | os.X_OK, path=None) // 可執(zhí)行文件路徑, path:要查找的路徑,未指定使用os.environ的結(jié)果
path_str = shutil.which("python")
# 異常
try: pass
except shutil.SameFileError: pass # copyfile()時,源和目錄是同一個文件時,拋此異常
except shutil.Error: pass # copytree()時, 多文件操作時引發(fā)的異常, 異常包含(srcname, dstname, excinfo)
# 壓縮文件操作 (封裝了zipfile / tarfile)
# 創(chuàng)建歸檔文件 base_name:壓縮包文件名, format:格式 zip / tar / bztar / xztar / gztar, root_dir:被歸檔的根目錄(默認當前目錄)
# base_dir:保存歸檔文件的目錄(默認當前目錄) verbose:已棄用 dry_run:True(不創(chuàng)建歸檔,但記錄日志), owner:用戶, group:用戶組, logger:日志
# shutil.make_archive(base_name, format[, root_dir[, base_dir[, verbose[, dry_run[, owner[, group[, logger]]]]]]])
dst = shutil.make_archive('Box', 'zip', 'temp') # 注意:root_dir / base_dir至少寫一個,不然會造成壓縮包再次被打包的情況
# 分拆歸檔, filename:文件名, extract_dir:解壓到目錄(默認當前目錄), format:格式 (未提供,根據(jù)擴展名查找,未找到引發(fā)ValueError)
# shutil.unpack_archive(filename[, extract_dir[, format]])
shutil.unpack_archive('Box.zip')
lists = shutil.get_archive_formats() # 返回支持的歸檔格式列表[(format, info)]
lists = shutil.get_unpack_formats() # 返回所有注冊格式的列表[(name, extensions, description)]
# 注冊壓縮格式, name:格式名, function:def func(base_name, base_dir, owner, group, dry_run, logger), extra_args:額外參數(shù), description:說明信息
# shutil.register_archive_format(name, function[, extra_args[, description]])
# shutil.unregister_archive_format(name) // 注銷壓縮格式
# 注冊解壓格式 name:格式名, extensions:擴展名列表, function:實現(xiàn)函數(shù) def unpack(filename, extract_dir), extra_args:額外參數(shù)(name, value), description:說明
# shutil.register_unpack_format(name, extensions, function[, extra_args[, description]])
# shutil.unregister_unpack_format(name) // 注銷解壓格式
# 終端
# shutil.get_terminal_size(fallback=(columns, lines))
columns, lines = shutil.get_terminal_size() # 查詢終端大小(寬, 高), 無法查詢返回默認大小(80, 24)
if __name__ == "__main__":
shutil_demo()
# shutil_func()
本文參與騰訊云自媒體分享計劃,歡迎正在閱讀的你也加入,一起分享。
知識點補充:
shutil 模塊
shutil可以簡單地理解為sh + util,shell工具的意思。shutil模塊是對os模塊的補充,主要針對文件的拷貝、刪除、移動、壓縮和解壓操作。
拷貝文件, shutil會自動識別拷貝的到底是文件還是文件夾, 如果存在同名的文件將會自動進行覆蓋。
以上就是腳本之家小編給大家整理的全部相關(guān)知識點,感謝大家的學習和支持。
相關(guān)文章
python實現(xiàn)K近鄰回歸,采用等權(quán)重和不等權(quán)重的方法
今天小編就為大家分享一篇python實現(xiàn)K近鄰回歸,采用等權(quán)重和不等權(quán)重的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-01-01
xshell會話批量遷移到mobaxterm的工具(python小工具)
這篇文章主要介紹了xshell會話批量遷移到mobaxterm的工具,使用方法也超級簡單,本文通過python代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-12-12
Python使用Oracle向量數(shù)據(jù)庫實現(xiàn)文本檢索系統(tǒng)
在本文中,我們將深入分析一個使用Oracle向量數(shù)據(jù)庫實現(xiàn)文本檢索系統(tǒng)的Python代碼,并基于相同的技術(shù)生成一個新的示例,這個系統(tǒng)允許我們存儲文檔及其嵌入向量,并執(zhí)行相似性搜索,感興趣的朋友可以參考下2024-07-07
Python實現(xiàn)按特定格式對文件進行讀寫的方法示例
這篇文章主要介紹了Python實現(xiàn)按特定格式對文件進行讀寫的方法,可實現(xiàn)文件按原有格式讀取與寫入的功能,涉及文件的讀取、遍歷、轉(zhuǎn)換、寫入等相關(guān)操作技巧,需要的朋友可以參考下2017-11-11
Python pyecharts Line折線圖的具體實現(xiàn)
折線圖在很多圖標中都有使用,本文主要介紹了Python pyecharts Line折線圖的具體實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-05-05

