forked from gxcuizy/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
zip.py
51 lines (43 loc) · 1.36 KB
/
zip.py
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
压缩和解压缩zip文件
author: gxcuizy
time:2018-08-13
"""
import zipfile
import os
def create_zip(path):
"""创建一个压缩文件"""
# 创建一个zip文件对象
zip_file = zipfile.ZipFile(os.path.basename(path) + ".zip", "w")
# 将文件写入zip文件中,即将文件压缩
print('开始压缩文件……')
for root, dirs, files in os.walk(path, topdown=False):
for name in dirs:
print("正在压缩文件夹:" + os.path.join(root, name))
zip_file.write(os.path.join(root, name))
for name in files:
print("正在压缩文件:" + os.path.join(root, name))
zip_file.write(os.path.join(root, name))
# 关闭zip文件对象
zip_file.close()
def uncompress_zip(path):
"""解压缩一个文件"""
print('正在解压文件中……')
zfile = zipfile.ZipFile(path, "r")
zfile.extractall()
# 程序主入口
if __name__ == "__main__":
# 打包(解压缩)的文件路径(文件名)
path_info = 'test.zip'
if os.path.isdir(path_info):
# 打包
create_zip(path_info)
print('压缩完成!')
elif os.path.isfile(path_info):
# 解压
uncompress_zip(path_info)
print('解压完成!')
else:
print('文件类型错误,请重试!')