You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python使用相对路径导入Excel文件报错问题求助

Fixing FileNotFoundError When Loading Excel from a Parent Directory

Hey there, let's break down why your relative path isn't working and get that Excel file loaded properly. The most common culprit here is confusing the script's location with Python's current working directory—they're not always the same!

Why Your Current Code Fails

When you use a path like ../B_folder/2_file.xlsx, Python looks for the file relative to the directory you're in when you run the script, not the directory where the script itself lives. For example:

  • If your script is in A_folder/script.py
  • But you run it from A_folder's parent directory (like python A_folder/script.py)
  • Then ../ points to the parent of the parent directory, not the parent of A_folder—so it can't find B_folder.

Solutions to Try

1. Build the Path Using the Script's Absolute Location (Most Reliable)

This method ensures you always target the correct file, no matter where you run the script from:

import os
import pandas as pd

# Get the full path of your script
script_full_path = os.path.abspath(__file__)
# Get the directory where the script is stored
script_directory = os.path.dirname(script_full_path)
# Build the path to your Excel file
excel_path = os.path.join(script_directory, "..", "B_folder", "2_file.xlsx")
# Normalize the path to fix any slash/backslash inconsistencies
excel_path = os.path.normpath(excel_path)

# Now load the file
df = pd.read_excel(excel_path)

os.path.join handles cross-platform slash differences automatically, and os.path.normpath cleans up any messy path segments (like double dots or mixed slashes).

2. Switch to the Script's Directory First

If you prefer using relative paths, you can change Python's working directory to match your script's location first:

import os
import pandas as pd

# Get the script's directory
script_directory = os.path.dirname(os.path.abspath(__file__))
# Change the working directory to this folder
os.chdir(script_directory)

# Now your original relative path will work
df = pd.read_excel(r"../B_folder/2_file.xlsx")

3. Use a Full Absolute Path (Quick Test)

For quick debugging, you can hardcode the absolute path to the file (though this isn't ideal for portable code):

# Windows example
df = pd.read_excel(r"C:\YourProjectRoot\B_folder\2_file.xlsx")

# macOS/Linux example
df = pd.read_excel("/home/yourname/Projects/B_folder/2_file.xlsx")

How to Diagnose the Issue

If you're still stuck, print your current working directory to see where Python is looking:

import os
print("Current working directory:", os.getcwd())

This will show you exactly where Python is trying to find ../B_folder/2_file.xlsx—you'll likely see it's not the directory you expected.

内容的提问来源于stack exchange,提问作者MaMo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:06:35