溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

shutil模塊如何在Python3中使用

發(fā)布時(shí)間:2021-03-18 16:49:50 來(lái)源:億速云 閱讀:198 作者:Leah 欄目:開(kāi)發(fā)技術(shù)

本篇文章為大家展示了shutil模塊如何在Python3中使用,內(nèi)容簡(jiǎn)明扼要并且容易理解,絕對(duì)能使你眼前一亮,通過(guò)這篇文章的詳細(xì)介紹希望你能有所收獲。

1、shutil是shell

utility的縮寫(xiě)

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)

  # 獲取磁盤(pán)使用空間
  total, used, free = shutil.disk_usage(".")
  print("當(dāng)前磁盤(pán)共: %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(".") # 給定路徑的磁盤(pán)使用情況統(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至少寫(xiě)一個(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) // 注銷(xiāo)壓縮格式
  # 注冊(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) // 注銷(xiāo)解壓格式



  # 終端
  # 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()

shutil 模塊

shutil可以簡(jiǎn)單地理解為sh + util,shell工具的意思。shutil模塊是對(duì)os模塊的補(bǔ)充,主要針對(duì)文件的拷貝、刪除、移動(dòng)、壓縮和解壓操作。

拷貝文件, shutil會(huì)自動(dòng)識(shí)別拷貝的到底是文件還是文件夾, 如果存在同名的文件將會(huì)自動(dòng)進(jìn)行覆蓋。

上述內(nèi)容就是shutil模塊如何在Python3中使用,你們學(xué)到知識(shí)或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識(shí)儲(chǔ)備,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI