【问题标题】:xlrd throws TypeError: embedded NUL character when trying to open an `.xls` file from web in Python 3.4xlrd 在 Python 3.4 中尝试从 Web 打开“.xls”文件时抛出 TypeError: embedded NUL character
【发布时间】:2015-06-06 05:06:32
【问题描述】:

我正在尝试从网络打开一个 excel 文件并提取其中一列。但是,当我尝试使用 xlrd 打开文件时,出现错误。我正在尝试的代码是:

from urllib.request import urlopen
import xlrd
DJIA_URL = 'http://www.djaverages.com/?go=export-components&symbol=DJI'
xlfile = urlopen(DJIA_URL).read()
xlbook = xlrd.open_workbook(xlfile)

但是,我收到一个类型错误:

Traceback (most recent call last):
  File "C:\Code\development\Pynance\pynance\sources\indices.py", line 31, in <module>
    xlbook = xlrd.open_workbook(xlfile)
  File "C:\Python34\lib\site-packages\xlrd\__init__.py", line 394, in open_workbook
    f = open(filename, "rb")
TypeError: embedded NUL character
[Finished in 0.8s with exit code 1]

如果我手动下载文件并打开它:

xlfile = 'DJIComponents.xls'
xlbook = xlrd.open_workbook(xlfile)

没问题,我宁愿跳过手动步骤。是否有编码设置或我缺少的东西?

【问题讨论】:

    标签: python python-3.x typeerror urllib xlrd


    【解决方案1】:

    xlrd.open_workbook() 只能打开 excel 文件。但是xlfile = urlopen(DJIA_URL).read()创建的xlfile对象不是excel文件,所以xlbook = xlrd.open_workbook(xlfile)打不开。

    通过上述方式创建的xlfile 是“字节”类的对象。事实可以通过命令看到

    print(type(xlfile))

    这应该给

    &lt;class 'bytes'&gt;

    因此,您必须通过

    (1)添加

    import urllib.request

    (2)保存excel文件

    urllib.request.urlretrieve(DJIA_URL, r'path\to\file\xxx.xls')

    (3) 最后用

    打开它

    xlrd.open_workbook(r'path\to\file\xxx.xls')

    (在 python 3.4 eclipse PyDev win7 x64 上测试。)

    【讨论】:

    • 谢谢!我实际上能够通过以下方式避免显式保存文件:xl_file, headers = urlretrieve(DJIA_URL)xl_book = xlrd.open_workbook(xl_file),因为per the docs,“第二个参数,如果存在,指定要复制到的文件位置(如果不存在,该位置将是一个具有生成名称的临时文件)。”(强调我的)。是否有不属于 legacy interfaceurlretrieve 的不同功能?
    • 我建议转到urllib3my_pool = urllib3.PoolManager()....with my_pool.request('get', my_url, preload_content=False) as my_connection_obj, open(fname, 'wb') as my_file:....shutil.copyfileobj(my_connection_obj, my_file_out) 之类的东西可能会保存您的文件。 (抱歉无法在评论中排版)此外,如果您真的不喜欢显式保存文件,甚至可以使用tempfile.TemporaryFile() 创建自己的临时文件。
    猜你喜欢
    • 1970-01-01
    • 2017-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-02
    • 2021-10-28
    • 2021-06-13
    • 2020-03-20
    相关资源
    最近更新 更多