python - 如何在 python 中使用相对路径的目录上使用 zip.write()?
问题描述
我想为我的 zipfile 中的目录添加显式条目。例如我的 zipfile 包括:
assets/images/logo.png
实际上,我需要它包括:
assets/
assets/images/
assets/images/logo.png
所以我的问题是,如何使用相对路径将目录添加为显式条目?我尝试使用zip.write(relative/path/to/directory)
,但它说它找不到目录,因为它是相对路径。当我把它工作
/Users/i510118/Desktop/Engineering/kit-dev-portal-models/src/kit_devportal_models/static_data/static_extension/created_extnsn_version_update2/assets/images/logo.png
在 zipfile.write() 内部,但我需要它只是相对路径,这只是
assets/images/logo.png
这可能吗?
这是我的完整代码
buf = io.BytesIO()
zipObj = zipfile.ZipFile(buf, "w")
extension_folder = "created_extnsn_version_update2"
with zipObj:
# Iterate over all the files in directory
for folderName, subfolders, filenames in os.walk(path_to_extension_directory):
# If the folder is not the root folder the extension is in
if not folderName.endswith(extension_folder):
folder = folderName.split(f"{extension_folder}/", 1)[1]
else:
folder = ''
for filename in filenames:
# create complete filepath of file in directory
filePath = os.path.relpath(os.path.join(folderName, filename), path_to_extension_directory)
with open(f"{folderName}/{filename}", 'rb') as file_data:
bytes_content = file_data.read()
# Add folder to zip if its not the root directory
if folder:
zipObj.write(folder)
# Add file to zip
zipObj.writestr(filePath, bytes_content)
# edit zip file to have all permissions
zf = zipfile.ZipFile(buf, mode='a')
info = zipfile.ZipInfo(f"{folderName}/{filename}")
info.external_attr = 0o777 << 16
zf.writestr(info, f"{folderName}/{filename}")
# Rewind the buffer's file pointer (may not be necessary)
buf.seek(0)
return buf.read()
如果您需要更多信息,请告诉我!
解决方案
import zipfile
zf = zipfile.ZipFile('test.zip', 'w')
folders = [
"assets/",
"assets/images/",
]
for n in folders:
zfi = zipfile.ZipInfo(n)
zf.writestr(zfi, '')
zf.write('logo.png', 'assets/images/logo.png')
zf.close()
zf = zipfile.ZipFile('test.zip', 'r')
for i in zf.infolist():
print(f"is_dir: {i.is_dir()}; filename: {i.filename}")
zf.close()
推荐阅读
- databricks - Databricks cli 身份验证失败
- javascript - 隐藏所有id不是所选值的tr
- php - 使用正则表达式拆分未包含在 div 或 Table 中的段落
- java - JSON-Binding API - 反序列化多态对象
- elasticsearch - elasticsearch 6.8 - 通过将嵌套字段与文档中的另一个字段进行比较来过滤
- asp.net - 将字体添加到 4.8-windowsservercore-ltsc2019 图像
- r - 替换为 na 的值,仍然显示在 summary() 中
- java - JAVA RMI如何获取客户端调用方法的参数
- ios - Ionic WKWeabView 打破 iOS 上的模板
- c# - 我的 ConnectionString 有什么问题?当我在 Postman 中测试我的 API 时出现错误