【问题标题】:Python: Pandas read_excel cannot open .xls file, ValueError: File is not a recognized excel filePython:Pandas read_excel 无法打开 .xls 文件,ValueError:文件不是可识别的 excel 文件
【发布时间】:2021-09-02 05:16:23
【问题描述】:

问题:

当我尝试使用pd.read_excel(“NDC 数据库文件 - Excel 版本(zip 格式)”从https://www.fda.gov/drugs/drug-approvals-and-databases/national-drug-code-directory 下载)打开product.xls 时出错

df_product = pd.read_excel("tmp/Presentaciones.xls")

Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/usr/local/lib/python3.9/site-packages/pandas/util/_decorators.py", line 299, in wrapper
    return func(*args, **kwargs)
  File "/usr/local/lib/python3.9/site-packages/pandas/io/excel/_base.py", line 336, in read_excel
    io = ExcelFile(io, storage_options=storage_options, engine=engine)
  File "/usr/local/lib/python3.9/site-packages/pandas/io/excel/_base.py", line 1071, in __init__
    ext = inspect_excel_format(
  File "/usr/local/lib/python3.9/site-packages/pandas/io/excel/_base.py", line 965, in inspect_excel_format
    raise ValueError("File is not a recognized excel file")
ValueError: File is not a recognized excel file

我的环境:

pandas version: 1.2.4
xlrd version: 2.0.1
openpyxl version: 3.0.7

提前致谢。

【问题讨论】:

  • 我下载了文件并尝试使用不同的引擎读取它,但每次都会出错。如果没有解决办法,你可以在MS Excel中打开文件并保存为CSV,然后你可以用read_csv阅读它
  • 问题是文件根本不是 Excel(既不是 BIFF 也不是 OOXML),而是 CSV(字符分隔,这里使用制表符作为分隔符)。只需重命名文件并将 read_csv 与相关选项一起使用。并将问题报告给网站所有者,以便他们至少可以更正标签!
  • @CharlieClark 我在直接重命名为 csv 后对其进行了测试,它现在可以与 read csv 一起使用。谢谢

标签: python excel pandas openpyxl xlrd


【解决方案1】:

我遇到了类似的问题,我必须读取文件夹中的一堆 .xls 文件并将其合并到一个数据帧中。原来出现错误是因为 .txt 文件被强制保存为 .xls 文件。尝试打开文件时,这也会在 excel 中产生错误,说明

“'filename.xls'的文件格式和扩展名不匹配。文件 可能已损坏或不安全。除非你相信它的来源,否则不要打开 它。还是要打开吗?”

执行以下操作为我解决了这个问题:

import glob 
import os 
import pandas as pd

path = r'C:\tmp' ## use your path

all_files = glob.glob(os.path.join(path, "*.xls"))
df_from_each_file = (pd.read_csv(f, delimiter = "\t") for f in all_files) ## reading the files using csv reader with tab delimiter
df1   = pd.concat(df_from_each_file, ignore_index=True)  ## concatenating all the individual files

如果 pd.read_csv 不起作用,您还可以尝试检查 python 上的哪个文件阅读器能够读取您的原​​始文件格式。

P.S:根据 Yona 的评论编辑

【讨论】:

  • Alakananda Giridhar,您的解决方案也对我有用。但是,如果您只是使用 read_csv 读取 xls 文件,它也可以工作。你真的不需要在它之前将扩展名更改为txt。
猜你喜欢
  • 2021-06-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-10
  • 1970-01-01
  • 2011-03-05
  • 2017-02-07
  • 1970-01-01
相关资源
最近更新 更多