Easton's Blog Easton's Blog
首页
  • 编程语言

    • Python
  • 框架

    • Django
  • Mdn (opens new window)
  • HTML
  • CSS
  • JavaScript
  • Mysql
  • PostgreSQL
  • Elasticsearch
  • MongoDB
  • Redis
  • 服务器命令
  • Docker
  • GIT
  • 摄影
  • 草稿
  • 归类方式

    • 分类
    • 标签
    • 归档
  • 关于博客

    • 博客教程
    • 友情链接
    • 关于
导航站
GitHub (opens new window)

Easton Yang

爱生活😊爱学习
首页
  • 编程语言

    • Python
  • 框架

    • Django
  • Mdn (opens new window)
  • HTML
  • CSS
  • JavaScript
  • Mysql
  • PostgreSQL
  • Elasticsearch
  • MongoDB
  • Redis
  • 服务器命令
  • Docker
  • GIT
  • 摄影
  • 草稿
  • 归类方式

    • 分类
    • 标签
    • 归档
  • 关于博客

    • 博客教程
    • 友情链接
    • 关于
导航站
GitHub (opens new window)
  • Python

    • Python学习

    • 代码

      • aes案例
      • hashlib案例
      • log案例
      • sftp案例
      • 单例
      • zip压缩案例
        • 案例
    • 数据结构与算法

  • Django

  • 后端
  • Python
  • 代码
eastonyangxu
2023-09-04
目录

zip压缩案例

# 案例

# from StringIO import StringIO  # for Python 2
import gzip
import io
import os
import shutil
import tarfile
import zipfile

"""
各种压缩 gz,zip,tar.gz
tarfile:主要用于压缩或解压tar,tar.gz,可以选择不同的mode
gzip:主要用于压缩或解压gz格式
zipfile:主要用于压缩或解压zip格式
"""


def gz_stream2str(stream):
    """
    格式:gz (gz数据流解压为字符串)
    压缩后的数据流解压为字符串
    :param stream:
    :return:
    """
    buf = io.BytesIO(stream)
    f = gzip.GzipFile(mode='rb', fileobj=buf)
    try:
        data = f.read()
    finally:
        f.close()
    return data.decode('utf-8')


def gz_str2stream(data):
    """
    格式:gz(字符串压缩为gz数据流)
    字符串压缩为数据流
    :param data:
    :return:
    """
    buf = io.BytesIO()
    f = gzip.GzipFile(mode='wb', fileobj=buf)
    try:
        data = data.encode('utf-8') if isinstance(data, str) else data
        f.write(data)
    finally:
        f.close()
    return buf.getvalue()


def gzip_stream2str(stream):
    """
    格式:tar.gz (tar.gz数据流解压为字符串)
    :param stream:
    :return:
    """
    buf = io.BytesIO(stream)
    with tarfile.open(mode='r:gz', fileobj=buf) as t:
        return t.extractfile(t.getmember('tar')).read().decode('utf-8')


def gzip_str2stream(data):
    """
    格式:tar.gz(字符串压缩为tar.gz数据流)
    字符串压缩为数据流
    :param data:
    :return:
    """
    data = data.encode('utf-8') if isinstance(data, str) else data
    buf = io.BytesIO()
    tarinfo = tarfile.TarInfo('tar')
    tarinfo.size = len(data)
    with tarfile.open(mode='w:gz', fileobj=buf) as t:
        t.addfile(tarinfo, fileobj=io.BytesIO(data))
    return buf.getvalue()


def file2zip(zip_file_path, file_path, delete=True):
    """
    格式:zip,文件夹压缩
    :param delete: 是否删除删除源文件,默认删除
    :param zip_file_path: 压缩后的文件全路径
    :param file_path: 需要压缩的文件全路径
    :return:
    """
    z = zipfile.ZipFile(zip_file_path, "w", zipfile.ZIP_DEFLATED)
    if os.path.isdir(file_path):
        for path, dir_names, filenames in os.walk(file_path):
            for filename in filenames:
                z.write(os.path.join(path, filename))
    else:
        z.write(file_path)
    z.close()
    if delete:
        remove_path(file_path)


def zip2file(zip_file_name, extract_path, members=None, pwd=None, delete=False):
    """
    格式:zip,压缩文件内容提取值指定的文件夹
    :param delete: 是否删除删除源文件,默认不删除
    :param zip_file_name: 待解压的文件
    :param extract_path:  提取文件保存的目录
    :param members:       指定提取的文件,默认全部
    :param pwd:           解压文件的密码
    :return:
    """
    with zipfile.ZipFile(zip_file_name) as zf:
        zf.extractall(extract_path, members=members, pwd=pwd)
    if delete:
        remove_path(zip_file_name)


def file2gzip(zip_file_path, file_path, delete=True):
    """
    格式:tar.gz,文件压缩
    :param delete: 是否删除删除源文件,默认删除
    :param zip_file_path: 压缩后的文件全路径
    :param file_path: 需要压缩的文件全路径
    :return:
    """
    with tarfile.open(zip_file_path, "w:gz") as t:
        t.add(file_path, arcname=os.path.basename(file_path))
    if delete:
        remove_path(file_path)


def gzip2file(zip_file_name, extract_path, members=None, delete=False):
    """
    格式:tar.gz,压缩文件内容提取值指定的文件夹
    :param delete: 是否删除删除源文件,默认不删除
    :param zip_file_name: 待解压的文件
    :param extract_path:  提取文件保存的目录
    :param members:       指定提取的文件,默认全部
    :return:
    """
    with tarfile.open(zip_file_name) as t:
        t.extractall(path=extract_path, members=members)
    if delete:
        remove_path(zip_file_name)


def remove_path(file_path):
    # 删除文件或目录
    if os.path.isdir(file_path):
        shutil.rmtree(file_path)
    else:
        os.remove(file_path)


# py2的用法
# def maes_de(data, key, iv):
#     # # aes解密 CBC ,padding:PKCS7
#     cipher = AES.new(key, AES.MODE_CBC, iv)
#     msg = cipher.decrypt(data)
#     padding_len = ord(msg[len(msg) - 1])
#     return msg[0:-padding_len]
#
#
# def gzip_stream2str(stream):
#     # 压缩后的数据流解压为字符串
#     buf = StringIO.StringIO(stream)
#     f = gzip.GzipFile(mode='rb', fileobj=buf)
#     try:
#         data = f.read()
#     finally:
#         f.close()
#     return data

if __name__ == '__main__':
    test_data = 'hello'
    res_stream = gzip_str2stream(test_data)
    print(res_stream)
    print(gzip_stream2str(res_stream))

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
#Python
上次更新: 2023/09/04, 18:39:45
单例
排序

← 单例 排序→

最近更新
01
攻略制作要点
07-18
02
摄影主题拍摄
07-18
03
延时摄影剧本
07-18
更多文章>
Theme by Vdoing | Copyright © 2023-2024 Easton Yang | MIT License
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式