如何在Python中读取压缩文件夹中的文本文件

Chu*_*Nan 10 python zip python-2.7

我有一个压缩数据文件(全部在文件夹中,然后压缩).我想在不解压缩的情况下阅读每个文件.我尝试了几种方法,但没有任何方法可以输入zip文件中的文件夹.我该怎么做?

没有zip文件夹中的文件夹:

with zipfile.ZipFile('data.zip') as z:
  for filename in z.namelist():
     data = filename.readlines()
Run Code Online (Sandbox Code Playgroud)

有一个文件夹:

with zipfile.ZipFile('data.zip') as z:
      for filename in z.namelist():
         if filename.endswith('/'):
             # Here is what I was stucked
Run Code Online (Sandbox Code Playgroud)

ale*_*cxe 20

namelist() 以递归方式返回存档中所有项目的列表.

您可以通过调用os.path.isdir()来检查项是否是目录:

import os
import zipfile

with zipfile.ZipFile('archive.zip') as z:
    for filename in z.namelist():
        if not os.path.isdir(filename):
            # read the file
            with z.open(filename) as f:
                for line in f:
                    print line
Run Code Online (Sandbox Code Playgroud)

希望有所帮助.


Ric*_*chS 5

我让亚历克的代码工作。我做了一些小的编辑:(注意,这不适用于受密码保护的 zipfile)

import os
import sys
import zipfile

z = zipfile.ZipFile(sys.argv[1])  # Flexibility with regard to zipfile

for filename in z.namelist():
    if not os.path.isdir(filename):
        # read the file
        for line in z.open(filename):
            print line
        z.close()                # Close the file after opening it
del z                            # Cleanup (in case there's further work after this)
Run Code Online (Sandbox Code Playgroud)