猿问

如何将 ZipFile 对象转换为支持缓冲区 API 的对象?

我有一个 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


达令说
浏览 105回答 1
1回答

慕容森

或者,如果 API 需要类似文件的对象,您可以在创建 zip 文件时传递BytesIO实例并将其传递给 APIimport iodef 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()
随时随地看视频慕课网APP

相关分类

Python
我要回答