将zipfile解压缩代码从ruby转换为python

时间:2016-03-21 07:09:58

标签: python ruby zipfile

我正在将代码从ruby转换为python,它提取zipfile的内容。

我是python的新手,不知道如何准确转换下面的代码。

ruby​​代码:

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

这是我的python代码:

def extract_from_zipfile(inzipfile):

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

它将值返回为none。 请帮忙。

1 个答案:

答案 0 :(得分:2)

在ruby版本中,Option Explicit '****************************************************** '*** needs reference to Microsoft Scripting Runtime *** '****************************************************** Sub GetRandomSamples() Dim oDicSam As Dictionary Dim iCounter As Integer, k As Variant, iRandom As Integer, iRndMin As Integer, iRndMax As Integer, j As Integer Dim source As Worksheet, target As Worksheet On Error GoTo Err_GetRandomSamples Set source = ThisWorkbook.Worksheets(1) Set target = ThisWorkbook.Worksheets(2) 'define the range for randomizing iRndMin = 1 iRndMax = 500 'define the numbers of records for each column Set oDicSam = New Dictionary oDicSam.Add "AA", 4 oDicSam.Add "BB", 1 oDicSam.Add "CC", 1 oDicSam.Add "DD", 3 oDicSam.Add "EE", 1 j = 1 Randomize For Each k In oDicSam.Keys For iCounter = 1 To oDicSam.Item(k) iRandom = Int((iRndMax - iRndMin + 1) * Rnd + iRndMin) 'MsgBox "Random number for '" & k & "' is: " & iRandom, vbInformation, "Randomizing - " & iCounter source.Range(k & iRandom).Copy target.Range("A" & j) j = j + 1 Next Next Exit_GetRandomSamples: On Error Resume Next Set source = Nothing Set target = Nothing Set oDicSam = Nothing Exit Sub Err_GetRandomSamples: MsgBox Err.Description, vbExclamation, Err.Number Resume Exit_GetRandomSamples End Sub 将引用最后提取的文件。

在Python中,您可以使用zipfile.ZipFile.namelist获取文件列表:

txtfile