Search code examples
pythondjangocsvzip

How to extract csv file from a zip and save it to disk in python?


I have a zip file that I receive from the user. The zip file contains a csv file which I need to save to a directory in my server. I am using django in my backend and this is what I do

from zipfile import ZipFile
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse

@csrf_exempt
def store_file(request):
    if request.method == "POST":
            user_id = request.POST.get("user_id")
            client_file = request.FILES['attachment']

            file_path = "/home/sr/uploads/"
            try:
                with ZipFile(client_file, 'r') as zip_ref:
                    csv_file = zip_ref.infolist()[0]

                with open(file_path + '%s' % csv_file, 'wb+') as dest:
                    for chunk in csv_file.chunks():
                        dest.write(chunk)
                # return success message
                return HttpResponse(0)
            except Exception as e:
                # return error message
                return HttpResponse(1)

But I get this error message

Traceback (most recent call last):
  File "/home/sr/scripts/interact.py", line 2364, in store_file
    for chunk in csv_file.chunks():
AttributeError: 'ZipInfo' object has no attribute 'chunks'

Now this is how I usually store a csv file when it comes to me as just a csv file. But now in this case, the csv file is inside a zip and so even after pulling the csv file from the zip, I can't save it in my server.

What am I doing wrong?


Solution

  • infolist() is a method returning "meta" info about files in achive. Instead of this you can use something like:

    csv_file = zip_ref.namelist()[0]
    data = zip_ref.read(csv_file)
    with open(file_path + '%s' % csv_file, 'wb+') as dest:
        dest.write(date)