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

读取Cleaned_Data文件夹中Excel文件时触发FileNotFoundError的技术问题咨询

Fixing FileNotFoundError When Loading Excel Files from a Directory

Hey there! Let’s sort out why you’re getting that frustrating FileNotFoundError when trying to read Excel files from your Cleaned_Data folder.

Why This Error Happens

The core issue here is how os.listdir() works:

  • When you run os.listdir(directory), it only returns the raw filenames (like sales_data.xlsx) of files in the folder, not their full file paths.
  • When you call pd.read_excel(filename), Python looks for that file in your current working directory (not the Cleaned_Data folder you specified). Since the file isn’t there, it throws the FileNotFoundError.

Quick Fixes to Try

Fix 1: Use os.path.join() to Build Full File Paths

This is a straightforward way to combine your target directory with each filename to get a complete, valid path:

import os
import pandas as pd

directory = r"C:\Users\andre\OneDrive\Desktop\python_web_scrapper\Cleaned_Data"
for filename in os.listdir(directory):
    if filename.endswith(".xlsx"):
        # Combine the directory path and filename to get the full path
        full_file_path = os.path.join(directory, filename)
        # Now read the file using the complete path
        df = pd.read_excel(full_file_path)
        # Add your processing logic here (e.g., print(df.head()))
        print(f"Successfully loaded: {filename}")

Fix 2: Use pathlib (Modern & Cleaner Approach)

Python’s pathlib module makes path handling much more intuitive. It automatically handles path separators across operating systems and lets you directly target files with specific extensions:

from pathlib import Path
import pandas as pd

# Convert your directory string to a Path object
directory = Path(r"C:\Users\andre\OneDrive\Desktop\python_web_scrapper\Cleaned_Data")
# Glob all .xlsx files in the directory (returns full paths automatically)
for file_path in directory.glob("*.xlsx"):
    df = pd.read_excel(file_path)
    # Process your DataFrame here
    print(f"Successfully loaded: {file_path.name}")

Quick Troubleshooting Tip

If you still run into issues, double-check:

  • That your directory path is spelled correctly (watch out for typos in folder names or OneDrive sync quirks).
  • That your files actually end with .xlsx (some might be .xls or have hidden extensions). You can verify this by enabling "File name extensions" in Windows File Explorer.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 16:52:48