前言:
在最近的后臺開發工作中,需要將服務器的指定文件夾壓縮,然后傳輸到前臺。shell的zip命令可以很方便的實現該需求,python也有對應的模塊,這里簡要記錄一下使用兩種方式壓縮文件的方法。
shell命令壓縮
def zip_file(dir_path, out_path):
# 先切換到要壓縮的的文件目錄下,然后再壓縮文件,防止壓縮的文件出現深層次的文件目錄
zip_shell = """
#!/bin/bash
cd {dir_path} && zip -r {out_path} *
"""
try:
result = os.popen(zip_shell.format(out_path=out_path, dir_path=dir_path)).read()
if result.lower().find("zip error") != -1: # 表示出錯
logger.error(result)
return None
else:
return out_path
except Exception as e:
logger.error(u"壓縮文件失敗:{}".format(e.message))
logger.error(traceback.format_exc())
return None
python的zipfile模塊壓縮
def zip_dir(dir_path, out_path):
"""
:brief 將目標文件夾壓縮為zip格式
:param dir_path: 目標文件夾路徑
:param out_path: 壓縮文件路徑(xxx.zip)
:return: 壓縮文件路徑
"""
try:
zip_obj = zipfile.ZipFile(out_path, "w", zipfile.ZIP_DEFLATED)
for path, dir_names, file_names in os.walk(dir_path):
# 去掉目標跟路徑,只對目標文件夾下邊的文件及文件夾進行壓縮
fpath = path.replace(dir_path, '')
for filename in file_names:
zip_obj.write(os.path.join(path, filename), os.path.join(fpath, filename))
zip_obj.close()
return out_path
except Exception as e:
logger.error(u"壓縮文件失敗:{}".format(e.message))
logger.error(traceback.format_exc())
return None