Python не может закрыть zipfile - PullRequest
       17

Python не может закрыть zipfile

0 голосов
/ 15 апреля 2019

Ошибка при закрытии zip-файла для итеративной загрузки и сохранения XML. Функция 'def' выдает ошибку по адресу zf.close. Необходимо предоставить более подробное описание того, откуда происходит ошибка.

import urllib.request
import shutil
import os
import zipfile
from lxml import objectify

url = 'https://www.markit.com/news/InterestRates_USD_20190409.zip'
file_name = 'C:\\Users\\Personal\\usd_20190409.zip'
file = 'InterestRates_USD_20190409.xml'

def zipload(url, file_name, file, date):
    with urllib.request.urlopen(url) as response, open(file_name, 'wb') as out_file:
        shutil.copyfileobj(response, out_file)

    zf = zipfile.ZipFile(file_name, 'r')

    root = objectify.parse(zf.open(file)).getroot()

    data=[]
    for i in range(len(root.getchildren())):
        data.append([child.text for child in root.getchildren()[i].getchildren()])

    data1 = []
    for i in range(len(root.getchildren()[4].getchildren())):
        data1.append([child.text for child in root.getchildren()[4].getchildren()[i].getchildren()])
    data2 = []
    for i in range(len(root.getchildren()[3].getchildren())):
        data2.append([child.text for child in root.getchildren()[3].getchildren()[i].getchildren()])

    y = pd.DataFrame(data2).append(pd.DataFrame(data1))
    y = y[y[2].values!=None]

    y.columns = ['tenor', 'date', date.strftime("%Y-%m-%d")]
    y = y.set_index('tenor')
    zf.close()
    return y

это цикл для его сохранения. Мне нужно, чтобы функция def была правильной, чтобы можно было генерировать цикл.

date_range = pd.bdate_range(start='4/01/2019', end='04/10/2019') # form is month, day, year

pd_store = pd.DataFrame()
for date in date_range:
    dateT = date.strftime("%Y%m%d")
    url = 'https://www.markit.com/news/InterestRates_USD_' + str(dateT) + '.zip'
    file_name = 'C:\\Users\\Personal\\usd_' + str(dateT) + '.zip'
    file = 'InterestRates_USD_' + str(dateT) + '.xml'
    pd_rate = zipload(url, file_name, file, date)
    pd_rate = pd_rate.drop(['date'], axis = 1).T
    pd_store = pd_store.append(pd_rate)
    os.remove(file_name) # clean up data so as not to store ridiculous data
...