-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcompress_all_in_dir.py
63 lines (54 loc) · 1.62 KB
/
compress_all_in_dir.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
52
53
54
55
56
57
58
59
60
61
62
63
"""
从一个文件夹中获取所有层级目录中的文件,然后压缩打包,支持zip和tar
"""
import fire
import os
import zipfile
import tarfile
def make_zip(source_dir, output):
"""
遍历出目录及其子目录中的所有文件,打包成zip
:param source_dir:
:param output:
:return:
"""
zipf = zipfile.ZipFile(output, 'w')
pre_len = len(os.path.dirname(source_dir))
for parent, dirnames, filenames in os.walk(source_dir):
for filename in filenames:
pathfile = os.path.join(parent, filename)
arcname = pathfile[pre_len:].strip(os.path.sep) # 相对路径
zipf.write(pathfile, arcname)
zipf.close()
def make_targz(source_dir, output):
"""
将目录整个打包
:param output:
:param source_dir:
:return:
"""
with tarfile.open(output, "w:gz") as tar:
tar.add(source_dir, arcname=os.path.basename(source_dir))
def make_targz_one_by_one(source_dir, output):
"""
遍历出目录及其子目录中的所有文件,打包成tar.gz
:param output:
:param source_dir:
:return:
"""
tar = tarfile.open(output, "w:gz")
for root, dir, files in os.walk(source_dir):
for file in files:
pathfile = os.path.join(root, file)
tar.add(pathfile)
tar.close()
def main(source_dir, output, ztype='tar.gz'):
if ztype == 'tar.gz':
make_targz_one_by_one(source_dir, output)
elif ztype == 'zip':
make_zip(source_dir, output)
else:
print('Not supported compress type!')
return
if __name__ == '__main__':
fire.Fire(main)