'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 1:[1]

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)

Solution 2:[2]

Since you are using PyFilesystem, you can open a S3 filesystem and a Zip filesystem, then use copy_file to copy between them.

Something like the following should work:

import os
from fs import open_fs
from fs.copy import copy_file

with open_fs(os.getenv('s3_sample_folder')) as s3_fs:
    with open_fs('zip://zipfile.zip', create=True) as zip_fs:
        for filename in file_names():
            copy_file(s3_fs, filename, zip_fs, filename)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Will McGugan