Python3 shutil(高級(jí)文件操作模塊)實(shí)例用法總結(jié)
1、shutil是shell
utility的縮寫
shutil.move直接從一個(gè)地方挪到另一個(gè)地方,而os.rename常常只能重命名,不能挪動(dòng)位置。
功能是:
>>>shutil.move('old.txt',r'c:datarchive')
>>>shutil.copy('old.txt',r'c:datarchive')
>>>os.remove('junk.dat')
2、高級(jí)文件操作(拷貝/移動(dòng)/壓縮/解壓縮)
#!/usr/bin/env python
# coding=utf-8
__author__ = 'zhuo'
__date__ = '2017/5/25'
# shutil_demo.py 高級(jí)文件操作(拷貝 / 移動(dòng) / 壓縮 / 解壓縮)
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)
# 移動(dòng)文件/目錄
shutil.move("root", "temp", copy_function=shutil.copy2)
# 獲取磁盤使用空間
total, used, free = shutil.disk_usage(".")
print("當(dāng)前磁盤共: %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)限 / 最后訪問(wèn)時(shí)間 / 上次修改時(shí)間 / 標(biāo)志), 其他不受迎影響
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)建時(shí)間,該時(shí)間可通過(guò)修改系統(tǒng)時(shí)間再創(chuàng)建文件來(lái)實(shí)現(xiàn))
dst = shutil.copy2('file.txt', 'temp.txt')
# shutil.ignore_patterns(*patterns)
# symlinks:True(復(fù)制鏈接) / False(復(fù)制文件), ignore=ignore_patterns("") // 忽略的文件, copy_function=自定義復(fù)制函數(shù), ignore_dangling_symlinks:True(忽略文件不存在異常) / False(錯(cuò)誤列表中添加異常)
# shutil.copytree(src, dst, symlinks=False, ignore=None, copy_function=copy2, ignore_dangling_symlinks=False) // 遞歸的復(fù)制根目錄下的整個(gè)目錄樹(shù)
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) // 刪除整個(gè)目錄樹(shù), ignore_errors:是否忽略刪除失敗錯(cuò)誤, onerror=def error(func, path, excinfo)
shutil.rmtree("temp", ignore_errors=True)
# shutil.move(src, dst, copy_function=copy2) // 遞歸移動(dòng)文件/目錄, 目錄存在則移動(dòng)目錄, 文件存在則覆蓋
dst = shutil.move("root", "temp", copy_function=shutil.copy2)
total, used, free = shutil.disk_usage(".") # 給定路徑的磁盤使用情況統(tǒng)計(jì)信息
# 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()時(shí),源和目錄是同一個(gè)文件時(shí),拋此異常
except shutil.Error: pass # copytree()時(shí), 多文件操作時(shí)引發(fā)的異常, 異常包含(srcname, dstname, excinfo)
# 壓縮文件操作 (封裝了zipfile / tarfile)
# 創(chuàng)建歸檔文件 base_name:壓縮包文件名, format:格式 zip / tar / bztar / xztar / gztar, root_dir:被歸檔的根目錄(默認(rèn)當(dāng)前目錄)
# base_dir:保存歸檔文件的目錄(默認(rèn)當(dāng)前目錄) 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至少寫一個(gè),不然會(huì)造成壓縮包再次被打包的情況
# 分拆歸檔, filename:文件名, extract_dir:解壓到目錄(默認(rèn)當(dāng)前目錄), format:格式 (未提供,根據(jù)擴(kuò)展名查找,未找到引發(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() # 返回所有注冊(cè)格式的列表[(name, extensions, description)]
# 注冊(cè)壓縮格式, name:格式名, function:def func(base_name, base_dir, owner, group, dry_run, logger), extra_args:額外參數(shù), description:說(shuō)明信息
# shutil.register_archive_format(name, function[, extra_args[, description]])
# shutil.unregister_archive_format(name) // 注銷壓縮格式
# 注冊(cè)解壓格式 name:格式名, extensions:擴(kuò)展名列表, function:實(shí)現(xiàn)函數(shù) def unpack(filename, extract_dir), extra_args:額外參數(shù)(name, value), description:說(shuō)明
# 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() # 查詢終端大小(寬, 高), 無(wú)法查詢返回默認(rèn)大小(80, 24)
if __name__ == "__main__":
shutil_demo()
# shutil_func()
本文參與騰訊云自媒體分享計(jì)劃,歡迎正在閱讀的你也加入,一起分享。
知識(shí)點(diǎn)補(bǔ)充:
shutil 模塊
shutil可以簡(jiǎn)單地理解為sh + util,shell工具的意思。shutil模塊是對(duì)os模塊的補(bǔ)充,主要針對(duì)文件的拷貝、刪除、移動(dòng)、壓縮和解壓操作。
拷貝文件, shutil會(huì)自動(dòng)識(shí)別拷貝的到底是文件還是文件夾, 如果存在同名的文件將會(huì)自動(dòng)進(jìn)行覆蓋。
以上就是腳本之家小編給大家整理的全部相關(guān)知識(shí)點(diǎn),感謝大家的學(xué)習(xí)和支持。
相關(guān)文章
超詳細(xì)注釋之OpenCV dlib實(shí)現(xiàn)人臉采集
這篇文章主要介紹了OpenCV dlib實(shí)現(xiàn)人臉采集,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-09-09
Python中實(shí)現(xiàn)定時(shí)任務(wù)常見(jiàn)的幾種方式
在Python中,實(shí)現(xiàn)定時(shí)任務(wù)是一個(gè)常見(jiàn)的需求,無(wú)論是在自動(dòng)化腳本、數(shù)據(jù)處理、系統(tǒng)監(jiān)控還是其他許多應(yīng)用場(chǎng)景中,Python提供了多種方法來(lái)實(shí)現(xiàn)定時(shí)任務(wù),包括使用標(biāo)準(zhǔn)庫(kù)、第三方庫(kù)以及系統(tǒng)級(jí)別的工具,本文將詳細(xì)介紹幾種常見(jiàn)的Python定時(shí)任務(wù)實(shí)現(xiàn)方式2024-08-08
pd.DataFrame統(tǒng)計(jì)各列數(shù)值多少的實(shí)例
今天小編就為大家分享一篇pd.DataFrame統(tǒng)計(jì)各列數(shù)值多少的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-12-12
Python接入MySQL實(shí)現(xiàn)增刪改查的實(shí)戰(zhàn)記錄
這篇文章主要給大家介紹了關(guān)于Python接入MySQL實(shí)現(xiàn)增刪改查的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-03-03
python 實(shí)現(xiàn)字符串下標(biāo)的輸出功能
這篇文章主要介紹了python 簡(jiǎn)單的實(shí)現(xiàn)字符串下標(biāo)的輸出,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-02-02
jupyter notebook參數(shù)化運(yùn)行python方式
這篇文章主要介紹了jupyter notebook參數(shù)化運(yùn)行python方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-04-04

