zipfile tarfile模块

zipfile --- 使用ZIP存档

这个模块提供了创建、读取、写入、添加及列出 ZIP 文件的工具
# 创建一个ZipFile对象, 可使用上下文管理 with
class zipfile.ZipFile(file, mode='r', compression=ZIP_STORED, 
                      allowZip64=True, compresslevel=None, *, strict_timestamps=True)
      参数: file表示文件的路径或类文件对象(path-like object)
           mode指示打开zip文件的模式, 默认为 r
               r  表示读取已经存在的 zip 文件
               w  表示新建一个zip文档或覆盖一个已存在的zip文档
               a  表示将数据追加到一个现存的zip文档中
               x  表示仅新建并写入新的文件

           compression表示在zip文档中使用的压缩方法
               zipfile.ZIP_STORED      仅存储,不会对文件进行压缩
               zipfile.ZIP_DEFLATED    对文件进行压缩
           如果要操作的zip文件超过2G,应该将allowZip64设置为True, 默认为True

# 压缩文件
zipfile.ZipFile()            # 写模式 w 打开或者新建压缩文件
zipfile.write(path,arcname)  # 向压缩文件中添加内容
zipfile.close()              # 关闭压缩文件

# 解压文件
zipfile.ZipFile()            # 读模式 r 打开压缩文件
zipfile.extractall(path)     # 解压所有文件到某个路径下
zipfile.extract(file,path)   # 解压指定文件到某个路径下
zipfile.close()        # 关闭压缩文件

# 查看压缩表中的文件名字
zipfile.namelist()

tarfile 模块可以用来读写 tar 归档,包括使用 gzip, bz2 和 lzma 压缩的归档

mode action
'r' or 'r:*' 打开和读取使用透明压缩(推荐)。
'r:' 打开和读取不使用压缩。
'r:gz' 打开和读取使用gzip 压缩。
'r:bz2' 打开和读取使用bzip2 压缩。
'r:xz' 打开和读取使用lzma 压缩。
'x' 或 'x:' 创建tarfile不进行压缩。如果文件已经存在,则抛出 FileExistsError 异常。
'x:gz' 使用gzip压缩创建tarfile。如果文件已经存在,则抛出 FileExistsError 异常。
'x:bz2' 使用bzip2 压缩创建tarfile。如果文件已经存在,则抛出 FileExistsError 异常。
'x:xz' 使用lzma 压缩创建tarfile。如果文件已经存在,则抛出 FileExistsError 异常。
'a' or 'a:' 打开以便在没有压缩的情况下追加。如果文件不存在,则创建该文件。
'w' or 'w:' 打开用于未压缩的写入。
'w:gz' 打开用于 gzip 压缩的写入。
'w:bz2' 打开用于 bzip2 压缩的写入。
'w:xz' 打开用于 lzma 压缩的写入。
压缩文件
tarfile.open(name=None, mode='r', fileobj=None, bufsize=10240, **kwargs) #创建或打开文件
tarfile.add(name, arcname=None) #向压缩文件中添加文件
tarfile.close()      #关闭文件


解压文件
tarfile.open(name=None, mode='r', fileobj=None, bufsize=10240, **kwargs) #读模式打开文件
tarfile.extractall(path=".") # 解压所有文件到某个路径下
tarfile.extract(file,path) # 解压指定文件到某个路径下
tarfile.close()      #关闭文件

# 追加
tarfile.open(name=None, mode='r', fileobj=None, bufsize=10240, **kwargs) # a 模式打开文件

# 查看压缩包中的内容
getnames()
posted @ 2021-02-08 20:00  EdenWu  阅读(60)  评论(0编辑  收藏  举报