各位用户为了找寻关于Python打包文件夹的方法小结(zip,tar,tar.gz等)的资料费劲了很多周折。这里教程网为您整理了关于Python打包文件夹的方法小结(zip,tar,tar.gz等)的相关资料,仅供查阅,以下为您介绍关于Python打包文件夹的方法小结(zip,tar,tar.gz等)的详细内容
本文实例讲述了Python打包文件夹的方法。分享给大家供大家参考,具体如下:
一、zip
? 1 2 3 4 5 6 7 8 9 10 11import
os, zipfile
#打包目录为zip文件(未压缩)
def
make_zip(source_dir, output_filename):
zipf
=
zipfile.ZipFile(output_filename,
'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()
二、tar/tar.gz
? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15import
os, tarfile
#一次性打包整个根目录。空子目录会被打包。
#如果只打包不压缩,将"w:gz"参数改为"w:"或"w"即可。
def
make_targz(output_filename, source_dir):
with tarfile.
open
(output_filename,
"w:gz"
) as tar:
tar.add(source_dir, arcname
=
os.path.basename(source_dir))
#逐个添加文件打包,未打包空子目录。可过滤文件。
#如果只打包不压缩,将"w:gz"参数改为"w:"或"w"即可。
def
make_targz_one_by_one(output_filename, source_dir):
tar
=
tarfile.
open
(output_filename,
"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()
希望本文所述对大家Python程序设计有所帮助。