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

使用Pywin32无法找到同目录Excel文件的问题与解决

使用Pywin32打开同目录Excel文件的路径问题

问题现象

  • 尝试带r前缀的路径写法:

    file = r'\SeniorCadets.xlsm'
    wb = xlApp.Workbooks.Open(file)
    

    报错提示:

    " Sorry, we couldn't find \SeniorCadets.xlsx. Is it possible it was moved, renamed or deleted?"

  • 直接使用文件名也无法定位文件:

    file = "SeniorCadets.xlsm"
    wb = xlApp.Workbooks.Open(file)
    

    报错提示:

    Sorry, we couldn't find SeniorCadets.xlsm. Is it possible it was moved, renamed or deleted?

  • 仅执行print(file)时输出正常,错误仅在调用xlApp.Workbooks.Open时触发。

补充代码细节

更新后的完整报错前代码(Excel文件与Python文件处于同一目录):

import os
import win32com.client as win32
from array import *
##Setup Outlook
olApp = win32.Dispatch('Outlook.Application')
olNS = olApp.GetNameSpace('MAPI')

##Setup Excel
os.chdir(r"fullFilePath")
xlApp = win32.Dispatch('Excel.Application')
xlApp.Visible = True
file = "SeniorCadets.xlsx"
wb = xlApp.Workbooks.Open(file)

即使直接使用文件名"SeniorCadets.xlsx"仍无法找到文件;去掉r前缀后,尝试"\SeniorCadets"、"\\SeniorCadets"写法,错误信息中始终多一个\。

解决方案

即使文件在同目录,仍需使用完整路径。可通过os.path库自动获取并构建完整路径,避免手动处理反斜杠的问题:

import win32com.client as win32
from os.path import (dirname, abspath,
                     join)

##Setup Excel
xlApp = win32.Dispatch('Excel.Application')

# 获取当前Python文件所在目录
root_dir = dirname(abspath(__file__))

file = "my_file_name.xlsm"

# 构建文件完整路径
full_path = join(root_dir, file)

print(full_path)

wb = xlApp.Workbooks.Open(full_path)

xlApp.Visible = True

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 19:45:36