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

xlwings脚本Python中运行正常,从Excel调用时出现文件找不到错误

解决从Excel调用Python脚本时的FileNotFoundError问题

问题根源

你遇到的核心问题是工作目录不匹配:手动在Python环境运行脚本时,当前工作目录(CWD)是脚本所在目录或你打开终端的目录;但从Excel调用时,Python的CWD会切换成Excel的默认工作目录(比如C:\Program Files\Microsoft Office\root\Office16或你的文档目录)。而你的get_txt_files函数只返回了文件名,没有和用户选择的目录拼接成完整路径,导致open(file)在错误的目录下查找文件,自然触发找不到文件的报错。

具体修复步骤

下面是针对你的代码的关键修改点:

1. 修改get_txt_files,返回完整文件路径

原来的函数只返回文件名,现在需要把目录路径和文件名拼接成完整路径:

def get_txt_files(directory_path: str) -> list:
    all_files = os.listdir(directory_path)
    # 用os.path.join拼接目录和文件名,生成完整路径
    txt_files = [os.path.join(directory_path, file) 
                 for file in all_files 
                 if file.lower().endswith(".txt")]
    return txt_files

2. 调整clean_null_bytes和tables_for_export适配完整路径

这两个函数现在接收的是完整路径,直接使用即可;同时tables_for_export中提取工作表名称时,要从完整路径中解析出文件名:

def clean_null_bytes(list_of_txt_files: list):
    for file_path in list_of_txt_files:
        with open(file_path, 'rb') as to_clean:
            raw_data = to_clean.read()
        clean_data = raw_data.replace(b'\x00', b'')
        with open(file_path, 'wb') as cleaned:
            cleaned.write(clean_data)
    return

def tables_for_export(list_of_txt_files: list) -> dict:
    for_export = {}
    for file_path in list_of_txt_files:
        # 从完整路径中提取不带后缀的文件名
        file_name = os.path.splitext(os.path.basename(file_path))[0]
        # 处理Excel工作表名称限制:移除非法字符,截断到31字符以内
        safe_sheet_name = file_name.replace('/', '_').replace('\\', '_').replace(':', '_').replace('*', '_').replace('?', '_').replace('"', '_').replace('<', '_').replace('>', '_').replace('|', '_')[:31]
        data_frame = pd.read_table(file_path)
        for_export.update({safe_sheet_name: data_frame})
    return for_export

3. 额外排查技巧

以后再遇到路径相关问题,可以在脚本开头添加一行代码打印当前工作目录,快速定位问题:

print(f"当前工作目录:{os.getcwd()}")

其他小优化

  • 你的open_folder函数中root.update后面少了括号,应该修正为root.update();
  • clean_null_bytes直接修改原文件,建议提前备份原文件或使用临时文件处理,避免意外破坏数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:35:31