3

I am converting a code from ruby to python that extracts the contents of a zipfile.

I am new to python and not sure how to exactly convert the below code.

ruby code:

def extract_from_zipfile(inzipfile)

  txtfile=""
  Zip::File.open(inzipfile) { |zipfile|
    zipfile.each { |file|
      txtfile=file.name
      zipfile.extract(file,file.name) { true }
    }
  }

  return txtfile
end

this is my python code:

def extract_from_zipfile(inzipfile):

 txtfile=""
 with zipfile.ZipFile(inzipfile,"r") as z:
  z.extractall(txtfile)
 return txtfile

it returns the value as none.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Harsha Jasti
  • 1,114
  • 1
  • 9
  • 25

1 Answers1

2

In ruby version, txtfile will refer the last extracted file.

In Python, you can get file list using zipfile.ZipFile.namelist:

def extract_from_zipfile(inzipfile):
    txtfile = ""
    with zipfile.ZipFile(inzipfile, "r") as z:
        z.extractall(txtfile)
        names = z.namelist()    # <---
        if names:               # <--- To prevent IndexError for empty zip file.
            txtfile = names[-1] # <---
    return txtfile
falsetru
  • 357,413
  • 63
  • 732
  • 636