Search code examples
pythonzippython-zipfile

Create zipfile at local and write files from s3


I am creating a zipfile on my local machine and would like to write files from s3. So far I'm unable to do it. Here's what I have in the mean time.

import os
import zipfile
from fs import open_fs

fs = open_fs(os.getenv('s3_sample_folder'))
file_names = file_names() #list of file names

with zipfile.ZipFile('zipfile.zip', mode='w') as zf:
   for file in file_names:
       with fs.open('/'+file, 'rb') as remote_file:
           content = remote_file.read()
           zf.write(content, basename(content))

Solution

  • The ZipFile.write method accepts a file name, not file content. You should use the ZipFile.writestr method instead to write file content to the zip file:

    zf.writestr(file, content)