【问题标题】:get file list of files contained in a zip file获取 zip 文件中包含的文件的文件列表
【发布时间】:2012-02-09 07:33:11
【问题描述】:

我有一个 zip 存档:my_zip.zip里面是一个txt文件,我不知道名字。我正在看Python的zipfile模块(http://docs.python.org/library/zipfile.html),但无法理解是什么我正在努力。

我将如何执行相当于“双击”zip 文件以获取 txt 文件然后使用 txt 文件的操作:

>>> f = open('my_txt_file.txt','r')
>>> contents = f.read()

【问题讨论】:

    标签: python zip zipfile


    【解决方案1】:
    import zipfile
    
    # zip file handler  
    zip = zipfile.ZipFile('filename.zip')
    
    # list available files in the container
    print (zip.namelist())
    
    # extract a specific file from the zip container
    f = zip.open("file_inside_zip.txt")
    
    # save the extraced file 
    content = f.read()
    f = open('file_inside_zip.extracted.txt', 'wb')
    f.write(content)
    f.close()
    

    【讨论】:

      【解决方案2】:
      import zipfile
      
      zip=zipfile.ZipFile('my_zip.zip')
      f=zip.open('my_txt_file.txt')
      contents=f.read()
      f.close()
      

      您可以查看文档here。特别是,namelist() 方法将为您提供 zip 文件成员的名称。

      【讨论】:

      • 我收到一条错误消息,提示“存档中没有名为 '' 的项目”。请注意,我不知道压缩文件的名称是什么(它与 zip 存档的名称不同)。
      【解决方案3】:

      您需要的是ZipFile.namelist(),它将为您提供存档所有内容的列表,然后您可以通过zip.open('filename_you_discover') 获取该文件的内容。

      【讨论】:

      猜你喜欢
      • 2019-05-12
      • 1970-01-01
      • 1970-01-01
      • 2020-12-28
      • 1970-01-01
      • 1970-01-01
      • 2021-05-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多