1

I want to upload zip file with .csv files and output zip file with .vm files. I use this code:

def csv_archive_to_vm(request):
response = HttpResponse(content_type='application/force-download')

work_string = ''

if request.method == "POST":
    ##reading input zip file
    input_file = request.FILES.get('file')
    zf = zipfile.ZipFile(input_file)
    for info in zf.infolist():
        ##reading files in archive
        path = re.search('(.*\.csv)', info.filename)
        path_name = re.search('(.*/)(.*\.csv)', info.filename)
        for string in zf.open(info.filename):

            quotes_search = re.search('"(.*)",\s*"(.*)",\s*"(.*)"', string)
            if quotes_search:
                descr = quotes_search.group(1)
                macro_name = quotes_search.group(2)
                say = quotes_search.group(3)

            new_lines_search = re.search('/n', say)
            if new_lines_search:
                say = re.sub('/n', '\n\t\t', say)
            ##making content for new files for new archive
            work_string = work_string + '##' + descr + '\n#macro(' + macro_name + ')\n\t#random()\n\t\t' + say + '\n\t#end\n#end\n\n'
        ##outputting new archive
        zipdata = StringIO()
        zf_create = zipfile.ZipFile(zipdata, mode='a')
        try:
            if path_name:
                zf_create.writestr(str(path_name.group(1)) + str(path_name.group(2))[0:-4] + '.vm', work_string)
        finally:
            zf_create.close()
        work_string = ''
        response = HttpResponse(zipdata.read())
        response['Content-Disposition'] = 'attachment; filename=assistant-linguistics_vm.zip'
        response['Content-Type'] = 'application/x-zip'

return response

but i get empty zip archive, with 0kb weight. What am i doing wrong? Thanks.

Max Rukhlov
  • 331
  • 3
  • 12
  • You `read` the zip file after you `close` it. I think you need the `StringIO` to get the memory version of the file. http://stackoverflow.com/questions/12881294/django-create-a-zip-of-multiple-files-and-make-it-downloadable – Edwin Lunando Jul 11 '15 at 09:24
  • @EdwinLunando Thx, it worked for me. But now if i have folders more than one in input zip (f.e. /en/file.csv, /ru/file.csv) i get output zip file with only one folder. – Max Rukhlov Jul 11 '15 at 13:09

0 Answers0