Traceback (most recent call last): File "/home/wushuai/hhu/recommender-system-for-ecommerce/inputMod.py", line 6, in <module> df = pd.read_excel("Online Retail.xlsx") File "/home/wushuai/hhu/recommender-system-for-ecommerce/venv/lib/python3.13/site-packages/pandas/io/excel/_base.py", line 495, in read_excel io = ExcelFile( io, ...<2 lines>... engine_kwargs=engine_kwargs, ) File "/home/wushuai/hhu/recommender-system-for-ecommerce/venv/lib/python3.13/site-packages/pandas/io/excel/_base.py", line 1550, in __init__ ext = inspect_excel_format( content_or_path=path_or_buffer, storage_options=storage_options ) File "/home/wushuai/hhu/recommender-system-for-ecommerce/venv/lib/python3.13/site-packages/pandas/io/excel/_base.py", line 1402, in inspect_excel_format with get_handle( ~~~~~~~~~~^ content_or_path, "rb", storage_options=storage_options, is_text=False ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ) as handle: ^ File "/home/wushuai/hhu/recommender-system-for-ecommerce/venv/lib/python3.13/site-packages/pandas/io/common.py", line 882, in get_handle handle = open(handle, ioargs.mode) FileNotFoundError: [Errno 2] No such file or directory: 'Online Retail.xlsx'
时间: 2025-05-13 20:12:40 浏览: 21
### 解决方案
当使用 `pandas` 的 `read_excel()` 函数读取 Excel 文件时,如果遇到 `FileNotFoundError` 错误,通常是因为指定的文件路径不正确或者文件不存在于该路径下。以下是可能的原因以及解决方案:
#### 1. **确认文件路径**
确保提供的路径是正确的,并且文件确实存在于该路径下。可以尝试打印当前工作目录来验证路径是否匹配:
```python
import os
print(os.getcwd()) # 打印当前的工作目录
```
如果文件不在当前工作目录中,则需要提供绝对路径或相对路径。
#### 2. **检查文件名拼写**
错误可能是由于文件名拼写错误引起的。请仔细核对文件名及其扩展名 `.xlsx` 是否完全一致[^1]。
#### 3. **使用绝对路径**
为了避免因相对路径引发的问题,建议直接使用文件的绝对路径。例如:
```python
file_path = r"C:\Users\User\Documents\data.xlsx"
df = pd.read_excel(file_path, engine='openpyxl')
```
#### 4. **确认文件是否存在**
可以通过 Python 检查文件是否存在:
```python
if os.path.exists(file_path):
print("文件存在")
else:
print("文件不存在")
```
如果结果显示文件不存在,请重新上传文件或将文件移动到指定位置[^5]。
#### 5. **设置正确的引擎**
对于 `.xlsx` 文件,默认推荐使用 `openpyxl` 引擎而不是 `xlrd`,因为后者仅支持旧版 `.xls` 格式的文件[^3]。因此,在调用 `pd.read_excel()` 时显式指定 `engine='openpyxl'` 是必要的:
```python
import pandas as pd
df = pd.read_excel('Online Retail.xlsx', engine='openpyxl')
```
#### 6. **处理编码问题**
有时文件名可能会涉及特殊字符或空格,这可能导致路径解析失败。为了防止此类问题发生,可以在字符串前加上 `r` 来创建原始字符串,从而避免转义符的影响[^4]:
```python
file_path = r'C:\path\to\your\file\Online Retail.xlsx'
df = pd.read_excel(file_path, engine='openpyxl')
```
---
### 完整代码示例
以下是一个完整的代码片段,用于解决上述提到的各种潜在问题:
```python
import pandas as pd
import os
# 设置文件路径
file_path = r"Online Retail.xlsx"
# 检查文件是否存在
if not os.path.exists(file_path):
raise FileNotFoundError(f"The file {file_path} does not exist.")
# 正确读取Excel文件
try:
df = pd.read_excel(file_path, engine='openpyxl')
print(df.head())
except Exception as e:
print(f"An error occurred: {e}")
```
---
###
阅读全文
相关推荐


















