无法打开已下载,解压缩并保存在python3中的文件

时间:2018-08-27 20:38:56

标签: 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_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:'ftp://ftp.ibge.gov.br/Precos_Indices_de_Precos_ao_Consumidor/IPCA/Serie_Historica/ipca_SerieHist.zip',将'ipca_SerieHist.zip'文件保存在HD中,然后解压缩并打开'ipca_201807SerieHist.xls'文件,Libre Office会识别该文件。 / p>

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

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

1 个答案:

答案 0 :(得分:0)

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

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

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