Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read text files in a zipped folder in Python

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?

Without folder in the zip file:

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

With one folder:

with zipfile.ZipFile('data.zip') as z:
      for filename in z.namelist():
         if filename.endswith('/'):
             # Here is what I was stucked
like image 475
ChuNan Avatar asked Mar 25 '14 21:03

ChuNan


1 Answers

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

You can check whether an item is a directory by calling 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

Hope that helps.

like image 132
alecxe Avatar answered Oct 01 '22 16:10

alecxe