Python 3.x 无法打开已下载、解压缩并保存在python3中的文件

Python 3.x 无法打开已下载、解压缩并保存在python3中的文件,python-3.x,zipfile,bytesio,Python 3.x,Zipfile,Bytesio,下面的代码下载一个zip文件,并存储其中包含的归档文件;它不会给出任何错误消息 from io import BytesIO import zipfile as zf from urllib.request import urlopen import pickle as pc # file manager resp = urlopen('ftp://ftp.ibge.gov.br/Precos_Indices_de_Precos_ao_Consumidor/IPCA/Serie_Histor

下面的代码下载一个zip文件,并存储其中包含的归档文件;它不会给出任何错误消息

from io import BytesIO
import zipfile as zf
from urllib.request import urlopen

import pickle as pc  # file manager
resp = urlopen('ftp://ftp.ibge.gov.br/Precos_Indices_de_Precos_ao_Consumidor/IPCA/Serie_Historica/ipca_SerieHist.zip')
zipfile = zf.ZipFile(BytesIO(resp.read()))

zipped_filenames = zipfile.namelist()
for filename in zipped_filenames:
    print('Filename: ', filename)

    xls_file = zipfile.read(filename)
    with open(filename, 'wb') as output:
        pc.dump(xls_file, output, pc.HIGHEST_PROTOCOL)
输出:

Filename:  ipca_201807SerieHist.xls
当我试图用Libre Office打开文件“ipca_201807SerieHist.xls”(用上述代码下载和提取)时,LO无法识别该文件并尝试导入它

如果我转到URL:'',将'ipca_SerieHist.zip'文件保存在HD中,然后提取并打开'ipca_201807SerieHist.xls'文件,Libre Office会识别该文件

两个文件“ipca_201807SerieHist.xls”的大小相似;下载的那个比62976字节稍大62994字节。 如果我比较一下内容,除了一些孤立的字符外,它们似乎非常相似


注:“ipca_201807SerieHist.xls”是葡萄牙语。

正如mkrieger1所提到的,只需将最后一行更改为以下内容即可解决问题

for filename in zipped_filenames:
    print('Filename: ', filename)

    xls_file = zipfile.read(filename)
    with open(filename, 'wb') as output:
        output.write(xls_file)

为什么使用
pickle.dump
而不使用
output.write