'Converting zipfile extracting code from ruby to python

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.



Solution 1:[1]

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

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 falsetru