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()
添加回答
舉報