0

我不明白为什么我不能提取文件以及为什么 Python 打印KeyError: There is no item named eurofxref.zip in the archive lang interpreter see file as eurofxref.csv

import os
import zipfile
from file_from_web_class import FileFromWeb

if __name__ == "__main__":
url = "https://www.ecb.europa.eu/stats/eurofxref/eurofxref.zip"
dir = point_file_from_cwd("temp", "eurofxref.zip")

with FileFromWeb(url, dir) as f:
    with zipfile.ZipFile(f.temp_file, "r") as z:
        path = point_from_cwd("temp")
        a_file = z.namelist()[0]
        print(a_file) #? eurofxref.csv
        os.chdir(path) 
        z.extract("eurofxref.zip", '.', None) #? I don't understand.

更多细节:

import os
import zipfile
import requests

class FileFromWeb:


def __init__(self, url, temp_file):
    self.url = url
    self.temp_file = temp_file


def __enter__(self):
    response = requests.get(self.url)
    with open(self.temp_file, "wb") as reading_file:
        reading_file.write(response.content)
    return self


def __exit__(self, exc_type, exc_val, exc_tb):
    pass

main.py文件上的方法:

def point_from_cwd(rel_path):
    defined_path = os.getcwd() + "\\" + rel_path 
    print("You want point dir: ", os.getcwd() + "\\" + rel_path)
    return defined_path

def point_file_from_cwd(rel_path, file_name):
    defined_path = os.getcwd() + "\\" + rel_path + "\\" + file_name 
    print("You want point file in dir: ", os.getcwd() + "\\" + rel_path +  "\\" + file_name)
    return defined_path
4

2 回答 2

2

KeyError 是一个不言自明的异常,它基本上说“档案中没有名为 eurofxref.zip 的项目,因此您可能正在尝试提取 eurofxref。csv但提供了错误的项目。

如果我通过给定的详细信息理解您的问题,则更改此行应该没问题:

z.extract("eurofxref.zip", '.', None) #? I don't understand.

作为:

z.extract("eurofxref.csv", '.', None) #? I don't understand.
于 2021-05-17T08:23:36.290 回答
0

ZipFile.extract仅从存档中提取指定的成员。尝试:

z.extract("eurofxref.csv", '.', None)

或者:

z.extractall()
于 2021-05-17T08:23:38.417 回答