构造文件内容写入压缩文件,并指定解压后的目录结构
import os as _os
import zipfile
def generateStartScript(zip_file):
"""
:type zip_file:zipfile.ZipFile
"""
# 文件内容
lines = []
lines.append("#!/bin/bash")
lines.append(_os.linesep)
lines.append('WORK_DIR=$(cd "$(dirname "$0")"; pwd)')
lines.append(_os.linesep)
lines.append('. $WORK_DIR/common.sh')
lines.append(_os.linesep)
lines.append("start_service %s" % "test")
lines.append(" --run-service %s" % "my_service")
lines.append(" --run-web %s --port %s" % ("my_web", "9999"))
lines.append(_os.linesep)
# 表示解压后生成shell目录,目录中有个文件为start-%s.sh
info = zipfile.ZipInfo("shell/start-%s.sh" % "test")
info.external_attr = 0o500 << 16
zip_file.writestr(info, "".join(lines))
# 构造压缩文件名称, w意思是写模式
with zipfile.ZipFile("D://a.zip", 'w') as zip_file:
generateStartScript(zip_file)
此代码可以直接用的,写下来方便大家,也方便以后查阅
压缩某个目录第一种写法
def xray_zipFolder(zip_file, full_path, target_path, ignore_path=None):
# 压缩文件写入
if not ignore_path is None:
if target_path in ignore_path:
return
if os.path.isdir(full_path):
for fname in os.listdir(full_path):
xray_zipFolder(zip_file, os.path.join(full_path, fname), target_path + '/' + fname, ignore_path)
else:
zip_file.write(full_path, target_path)
full_path = 'C:\\Users\\penggan\\Desktop\\logdir'
zip_file_path='C:\\Users\\penggan\\Desktop\ds\\a.zip'
with zipfile.ZipFile(zip_file_path, 'w',) as zip_file:
压缩某个目录第二种写法
def zip_directory(directory, zip_name):
# 这是chatgpt的压缩 代码
with zipfile.ZipFile(zip_name, 'w', zipfile.ZIP_DEFLATED) as zipf:
for root, dirs, files in os.walk(directory):
# root->当前目录 dirs->当前目录的子目录, files->当前目录的文件列表
father = root.replace(directory,"")
for file in files:
zipf.write(os.path.join(root, file),'xray/'+father+"/"+file)
source_dir = "C:\\Users\\penggan\\Desktop\\logdir"
zip_file_path = "C:\\Users\\penggan\\Desktop\ds\\a.zip"
zip_directory(source_dir,zip_file_path )
压缩某个目录第三种写法
def zip_directory(directory, zip_name):
with zipfile.ZipFile(zip_name, 'w', zipfile.ZIP_DEFLATED) as zipf:
for root, dirs, files in os.walk(directory):
# root->当前目录 dirs->当前目录的子目录, files->当前目录的文件列表
for file in files:
# 将要被写入的文件
des_file_path = os.path.join(root, file)
# 该文件的相对路径
relative_path = os.path.relpath(des_file_path,directory)
# 压缩后的文件目录为:test+相对路径
zipf.write(des_file_path,"test/"+relative_path)
source_dir = "C:\\Users\\penggan\\Desktop\\logdir"
zip_file_path = "C:\\Users\\penggan\\Desktop\ds\\a.zip"
zip_directory(source_dir,zip_file_path )