亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何將 ZipFile 對象轉換為支持緩沖區 API 的對象?

如何將 ZipFile 對象轉換為支持緩沖區 API 的對象?

達令說 2023-10-31 14:15:35
我有一個 ZipFile 對象,需要將其轉換為可與緩沖區 api 配合使用的對象。上下文是我正在嘗試使用一個 API,該 API 表示它需要一個類型為string($binary). 我該怎么做呢?我知道這是完全錯誤的,但這是我的代碼:    def create_extension_zip_file(self, path_to_extension_directory, directory_name):    zipObj = ZipFile("static_extension.zip", "w")    with zipObj:        # Iterate over all the files in directory        for folderName, subfolders, filenames in os.walk(path_to_extension_directory):            for filename in filenames:                # create complete filepath of file in directory                filePath = os.path.join(folderName, filename)                with open(filename, 'rb') as file_data:                    bytes_content = file_data.read()                # Add file to zip                zipObj.write(bytes_content, basename(filePath))    return zipObj
查看完整描述

1 回答

?
慕容森

TA貢獻1853條經驗 獲得超18個贊

或者,如果 API 需要類似文件的對象,您可以在創建 zip 文件時傳遞BytesIO實例并將其傳遞給 API

import io


def create_extension_zip_file(self, path_to_extension_directory, directory_name):

? ? buf = io.BytesIO()

? ? zipObj = ZipFile(buf, "w")

? ? with zipObj:

? ? ? ? # Iterate over all the files in directory

? ? ? ? for folderName, subfolders, filenames in os.walk(path_to_extension_directory):

? ? ? ? ? ? for filename in filenames:

? ? ? ? ? ? ? ? # create complete filepath of file in directory

? ? ? ? ? ? ? ? filePath = os.path.join(folderName, filename)

? ? ? ? ? ? ? ? with open(filename, 'rb') as file_data:

? ? ? ? ? ? ? ? ? ? bytes_content = file_data.read()

? ? ? ? ? ? ? ? # Add file to zip

? ? ? ? ? ? ? ? zipObj.write(bytes_content, basename(filePath))

? ? # Rewind the buffer's file pointer (may not be necessary)

? ? buf.seek(0)

? ? return buf

如果 API 需要 bytes 實例,您可以在寫入后以二進制模式打開 zip 文件,然后傳遞 bytes 。


with open('static_extension.zip', 'rb') as f:

? ? bytes_ = f.read()


查看完整回答
反對 回復 2023-10-31
  • 1 回答
  • 0 關注
  • 124 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號