5

【Python】zip

 3 years ago
source link: https://www.guofei.site/2018/09/27/zip.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

【Python】zip

2018年09月27日

Author: Guofei

文章归类: Python语法 ,文章编号: 1241


版权声明:本文作者是郭飞。转载随意,但需要标明原文链接,并通知本人
原文链接:https://www.guofei.site/2018/09/27/zip.html

Edit

先下载一个 zip 作为实验对象

import requests
url = 'https://github.com/guofei9987/datasets_for_ml/blob/master/MNIST/MNIST_data_csv.zip?raw=true'
r = requests.get(url)
with open('MNIST_data_csv.zip', 'wb') as f:
    f.write(r.content)
import zipfile
azip=zipfile.ZipFile('MNIST_data_csv.zip')
azip.namelist() # 所有的文件夹和文件
azip.filename # zip 文件名

azip_info = azip.getinfo('mnist_test_labels.csv') # 单个文件
azip_info.file_size,azip_info.compress_size  # 压缩前大小,压缩后大小
# read出来的是字节字符串,decode成utf-8即可
azip.read('mnist_test_labels.csv').decode('utf-8')
# azip.extract()
azip.extractall()
zfile.extractall(pwd=b'123') # 密码正确则解压,密码不正确则报错

压缩

# 新建压缩包,放文件进去,若压缩包已经存在,将覆盖。可选择用a模式,追加
azip = zipfile.ZipFile('bb.zip', 'w')
# 必须保证路径存在,将bb件夹(及其下aa.txt)添加到压缩包,压缩算法LZMA
azip.write('D:/bb/aa.txt', compress_type=zipfile.ZIP_LZMA)
# 写入一个新文件到压缩包中,data是该文件的具体内容,可以是str或者是byte。
# 这里是新建一个bb文件夹,其下再新建一个cc.txt,将hello world写入到文本中
azip.writestr('bb/cc.txt', data='Hello World', compress_type=zipfile.ZIP_DEFLATED)
# 关闭资源
azip.close()

上面有两个方法比较类似,注意区分。

write指的是将已经存在的文件复制到压缩包,包括路径中的所有文件夹河其下的文件。 writestr是直接在压缩包里新建文件夹和文件,data参数是往该文件中写入的内容。

azip.write(r'D:/bb', compress_type=zipfile.ZIP_LZMA)

参考文献

https://www.cnblogs.com/sun-haiyu/p/7082063.html


您的支持将鼓励我继续创作!

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK