Spyder已设当前工作目录,相对路径仍无法正常使用
问题:Outlook添加附件时提示路径不存在,变量未正确解析
我使用以下代码自动生成Outlook邮件并添加附件:
import pandas as pd import win32com.client as win32 import os os.chdir(directory where .py file is) # location for attachment attach_HS= str("/Returns/"+df['NAME'][ind]+"/HS_"+df['NAME'][ind]+"_2023_24.xlsx") # Open up an outlook email outlook = win32.gencache.EnsureDispatch('Outlook.Application') new_mail = outlook.CreateItem(0) # Label the subject frs = str(df['NAME'][ind]) subject = str(...) new_mail.Subject = subject # Add the to and cc list new_mail.SendUsingAccount = "x@x.uk" new_mail.To = str(df['MAIN_ CONTACT'][ind]) new_mail.CC = "x@x.uk" # add the body of the message message_body = "Hi "+df['NAME'][ind] # Attach the file attachment1 = attach_HS # The file needs to be a string not a path object new_mail.Attachments.Add(Source=str(attachment1)) # Display the email new_mail.Display(True)
运行时持续报错:
com_error: (-2147352567, 'Exception occurred.', (4096, 'Microsoft Outlook', 'Path does not exist. Verify the path is correct.', None, 0, -2147024893), None)
已在Spyder中设置当前工作目录,脚本开头也用os.chdir指定了.py文件所在目录,右侧文件浏览器可见Returns文件夹及内部目标文件,尝试将路径分隔符改为\也无效。报错时打印attachment1得到的路径格式如下(名称已脱敏):
'\\Returns\\df['NAME'][ind]\\LE_df['NAME'][ind]_2023_24.xlsx'
找不到该特定问题的解决方案,仅查到工作目录设置相关问题,恳请帮助。
解决方案
从打印的路径可以看出,df['NAME'][ind]并未被解析为实际的名称值,而是直接作为字符串拼入了路径,这是核心问题。以下是修复步骤:
先确认变量有效性
在拼接路径前,先打印df['NAME'][ind]的值,确认是否能输出实际名称:print("当前名称值:", df['NAME'][ind])如果输出的是
df['NAME'][ind]而非具体名称,说明df未正确加载或ind不是有效索引。改用更可靠的路径拼接方式
放弃直接字符串拼接,使用os.path.join和f-string来确保变量被正确解析,同时避免路径分隔符问题:# 提取实际名称 name = df['NAME'][ind] # 拼接相对路径 attach_HS = os.path.join("Returns", name, f"HS_{name}_2023_24.xlsx")使用绝对路径避免工作目录冲突
由于Outlook的工作目录可能与脚本不一致,建议生成绝对路径:# 获取脚本所在目录的绝对路径 script_dir = os.path.dirname(os.path.abspath(__file__)) # 拼接成绝对路径 attach_HS = os.path.join(script_dir, "Returns", name, f"HS_{name}_2023_24.xlsx")添加路径存在性检查
在添加附件前验证路径有效性,提前排查问题:if not os.path.exists(attach_HS): print(f"错误:文件不存在 - {attach_HS}") else: new_mail.Attachments.Add(Source=attach_HS)
内容的提问来源于stack exchange,提问作者Housepets
相关产品推荐
相关产品推荐

