Reputation: 1254
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.
Upvotes: 3
Views: 48
Reputation: 369274
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
Upvotes: 2