为什么我不能用 Python 提取文件

问题描述

我不明白为什么我无法提取文件以及为什么 Python 打印 KeyError: There is no item named eurofxref.zip in the archive lang 解释器将文件视为 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

ma​​in.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

解决方法

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

如果我通过给定的细节理解您的问题,那么当您更改此行时应该没问题:

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

作为:

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

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

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

或:

z.extractall()

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...