当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python shutil.unpack_archive()用法及代码示例


Python中的Shutil模块提供了许多对文件和文件集合进行高级操作的函数。它属于Python的标准实用程序模块。此模块有助于自动执行文件和目录的复制和删除过程。

shutil.unpack_archive()Python中的方法用于解压缩存档文件。

用法: shutil.unpack_archive(filename [, extract_dir [, format]])

参数:
filename:一个path-like对象,代表归档文件的完整路径。 path-like对象是表示路径的字符串或字节对象。
extract_dir(可选):path-like对象,表示解压缩归档文件的目标目录的路径。 path-like对象是表示路径的字符串或字节对象。这是一个可选参数,如果未提供,则将当前工作目录用作目标目录。
formats(可选):代表存档格式的字符串。格式的值可以是“zip”,“tar”,“gztar”,“bztar”或“xztar”中的任何一种,也可以是任何其他注册的拆包格式。这也是一个可选参数,如果未提供,则将归档文件名的扩展名用作格式。必须为此扩展程序注册一个拆包程序,否则将引发“ ValueError”异常。

返回类型:此方法不返回任何值。

代码1:使用shutil.unpack_archive()方法解压缩存档文件

# Python program to explain shutil.unpack_archive() method  
   
# importing shutil module  
import shutil 
  
# Full path of  
# the archive file 
filename = "/home/User/Downloads/file.zip"
  
# Target directory 
extract_dir = "/home/ihritik/Documnets"
  
# Format of archie file 
archive_format = "zip"
  
# Unpack the archive file  
shutil.unpack_archive(filename, extract_dir, archive_format)  
print("Archive file unpacked successfully.")
输出:
Archive file unpacked successfully.

代码2:使用shutil.unpack_archive()方法解压缩存档文件

# Python program to explain shutil.unpack_archive() method  
   
# importing shutil module  
import shutil 
  
# Full path of  
# the archive file 
filename = "/home/User/Downloads/file.zip"
  
  
# Unpack the archived file  
shutil.unpack_archive(filename)  
print("Archive file unpacked successfully.") 
  
# As extract_dir and format parameters 
# are not provided So, 
# shutil.unpack_archive() method will 
# unpack the archive file in  
# current working directory and extension 
# of the archive filename i.e zip 
# will be taken as format to unpack 
    
输出:
Archive file unpacked successfully.


相关用法


注:本文由纯净天空筛选整理自ihritik大神的英文原创作品 Python | shutil.unpack_archive() method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。