shutil 拷貝 / 移動 / 壓縮 / 解壓縮

來源:互聯網
上載者:User

標籤:忽略   arch   無法   zip   rbo   environ   leo   for   壓縮檔   

# 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]) // 拷貝檔案內容, 將fsrc檔案裡的內容copy到fdst檔案中, length:緩衝區大小      shutil.copyfileobj(open(‘file.txt‘, ‘r‘), open(‘temp.txt‘, ‘w‘))      # shutil.copyfile(src, dst, *, follow_symlinks=True) // 拷貝檔案內容, 同copyfileobj, 如果dst=src,拋SameFileError異常, dst存在則替換      dst = shutil.copyfile(‘file.txt‘, ‘temp.txt‘)      # shutil.copymode(src, dst, *, follow_symlinks=True) // 僅拷貝許可權, 其他資訊不受影響      shutil.copymode(‘file.txt‘, ‘temp.txt‘)      # shutil.copystat(src, dst, *, follow_symlinks=True) // 拷貝狀態(許可權 / 最後訪問時間 / 上次修改時間 / 標誌), 其他不受迎影響      shutil.copystat(‘file.txt‘, ‘temp.txt‘)      # shutil.copy(src, dst, *, follow_symlinks=True) // 拷貝檔案(資料 / 許可權)      dst = shutil.copy(‘file.txt‘, ‘temp.txt‘)      # shutil.copy2(src, dst, *, follow_symlinks=True) // 拷貝檔案(嘗試保留所有中繼資料) (不能拷貝建立時間,該時間可通過修改系統時間再建立檔案來實現)      dst = shutil.copy2(‘file.txt‘, ‘temp.txt‘)      # shutil.ignore_patterns(*patterns)      # symlinks:True(複製連結) / False(複製檔案), ignore=ignore_patterns("") // 忽略的檔案, copy_function=自訂複製函數, 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(".")  # 給定路徑的磁碟使用方式統計資訊      # shutil.chown(path, user=None, group=None) // 修改使用者和組 (Unix可用)      # shutil.which(cmd, mode=os.F_OK | os.X_OK, path=None) // 可執行檔路徑, path:要尋找的路徑,未指定使用os.environ的結果      path_str = shutil.which("python")          # 異常      try: pass      except shutil.SameFileError: pass  # copyfile()時,源和目錄是同一個檔案時,拋此異常      except shutil.Error: pass  # copytree()時, 多檔案操作時引發的異常, 異常包含(srcname, dstname, excinfo)            # 壓縮檔操作 (封裝了zipfile / tarfile)      # 建立歸檔檔案 base_name:壓縮包檔案名稱, format:格式 zip / tar / bztar / xztar / gztar, root_dir:被歸檔的根目錄(預設目前的目錄)      # base_dir:儲存歸檔檔案的目錄(預設目前的目錄) verbose:已棄用 dry_run:True(不建立歸檔,但記錄日誌), 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:格式 (未提供,根據副檔名尋找,未找到引發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:額外參數, description:說明資訊      # shutil.register_archive_format(name, function[, extra_args[, description]])      # shutil.unregister_archive_format(name) // 登出壓縮格式      # 註冊解壓格式 name:格式名, extensions:副檔名列表, function:實現函數 def unpack(filename, extract_dir), extra_args:額外參數(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 拷貝 / 移動 / 壓縮 / 解壓縮

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.