Как открыть и добавить вложенные zip-архивы в dataframe без распаковки? - PullRequest
0 голосов
/ 17 апреля 2019

Я пытаюсь открыть большое количество CSV-файлов, которые находятся в нескольких слоях ZIP-файлов. Учитывая природу этого проекта, я пытаюсь открыть, прочитать их в dataframe, добавить эти данные в совокупный dataframe, а затем продолжить через цикл.

Пример: каталог папок / первый почтовый индекс / второй почтовый индекс / третий почтовый индекс / csv file.csv

Мой существующий код может перебрать содержимое второго и третьего zip-файла и получить имя каждого CSV-файла. Я знаю, что этот код, вероятно, можно сделать более простым, импортировав glob, но я незнаком.

import os
import pandas as pd 
import zipfile, re, io
directory = 'C:/Test/'
os.chdir(directory)
fname = "test" + ".zip"
with zipfile.ZipFile(fname, 'r') as zfile:
    # second level of zip files
    for zipname in zfile.namelist():
        if re.search(r'\.zip$', zipname) != None:
            zfiledata = io.BytesIO(zfile.read(zipname))
            # third level of zip files
            with zipfile.ZipFile(zfiledata) as zfile2:
                for zipname2 in zfile2.namelist():
                    # this zipfile contains xml and csv contents. This filters out the xmls
                    if zipname2.find("csv") > 0:
                        zfiledata2 = io.BytesIO(zfile2.read(zipname2))
                        with zipfile.ZipFile(zfiledata2) as zfile3:
                            fullpath = directory + fname + "/" + zipname + "/" + zipname2 + "/"
                            # csv file names are always the same as their zips. this cleans the string.
                            csvf = zipname2.replace('_csv.zip',".csv")
                            filehandle = open(fullpath, 'rb')
                            # the above statement is erroring: FileNotFoundError: [Errno 2] No such file or directory:
                            zfilehandle = zipfile.ZipFile(filehandle)
                            data = []
                            csvdata = StringIO.StringIO(zfilehandle.read(csvf))
                            df = pd.read_csv(csvdata)
                            data.append(df)
print(data.head())

...