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

2024-04-26 10:56:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个压缩数据文件(都在一个文件夹中,然后压缩)。我想在不解压缩的情况下读取每个文件。我尝试了几种方法,但是没有任何方法可以在zip文件中输入文件夹。我该如何实现?

zip文件中没有文件夹:

with zipfile.ZipFile('data.zip') as z:
  for filename in z.namelist():
     data = filename.readlines()

只有一个文件夹:

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

Tags: 文件方法in文件夹fordata数据文件as
2条回答

我有亚历克的密码。我做了一些小修改:(注意,这对受密码保护的zipfiles不起作用)

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)

^{}递归返回存档中所有项的列表。

您可以通过调用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

希望能有所帮助。

相关问题 更多 >