Write to /tmp directory in aws lambda with python

点点圈 提交于 2019-12-03 03:15:50

extractAll() will extract files in the current directory, which is /var/task/test-deploy in your case.

You need to use os.chdir() to change the current directory:

import os, zipfile

os.chdir('/tmp')
with zipfile.ZipFile(source, 'r') as archive:
    archive.extractall()

Even better, you can create a temporary directory and extract the files there, to avoid polluting /tmp:

import os, tempfile, zipfile

with tempfile.TemporaryDirectory() as tmpdir:
    os.chdir(tmpdir)
    with zipfile.ZipFile(source, 'r') as archive:
        archive.extractall()

If you want to restore the current working directory after extracting the file, consider using this decorator:

import os, tempfile, zipfile, contextlib

@contextlib.context_manager
def temporary_work_dir():
    old_work_dir = os.getcwd()
    with tempfile.TemporaryDirectory() as tmp_dir:
        os.chdir(tmp_dir)
        try:
            yield
        finally:
            os.chdir(old_work_dir)

with temporary_work_dir():
    with zipfile.ZipFile(source, 'r') as archive:
        archive.extractall()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!