如何在 Python 中读取压缩文件夹中的文本文件 [英] How to read text files in a zipped folder in Python

查看:115
本文介绍了如何在 Python 中读取压缩文件夹中的文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a compressed data file (all in a folder, then zipped). I want to read each file without unzipping. I tried several methods but nothing works for entering the folder in the zip file. How should I achieve that?

zip 文件中没有文件夹:

Without folder in the zip file:

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

推荐答案

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

namelist() returns a list of all items in an archive recursively.

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

希望有所帮助.

这篇关于如何在 Python 中读取压缩文件夹中的文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆