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

os.startfile打开.max文件报错FileNotFoundError的问题求助

问题描述

需要实现以下功能:

  • 让用户选择目标目录
  • 列出目录中的.max文件
  • 在3ds Max未运行时,自动打开这些.max文件

但使用os.startfile()(也曾尝试subprocess)时出现报错:

FileNotFoundError: [WinError 2] 系统找不到指定的文件:

从程序输出能确认,代码可以正确识别目录路径及其中的.max文件,且之前曾用os.startfile()成功打开过.max文件,目前无法定位此次失败的原因。

相关代码如下:

import os
import psutil
import easygui
import time

from tkinter import filedialog
from tkinter import *

root = Tk()

msg = "Select a folder to render the .max files inside"
title = "3DS MAX AUTO RENDER"
choice = ["Select Folder"]
reply = easygui.buttonbox(msg, title, choices = choice)

if reply == "Select Folder":
    root.directoryPath = filedialog.askdirectory(initialdir="/", title="Select a folder")
    print(root.directoryPath)
    directoryFiles = os.listdir(root.directoryPath)
    print(directoryFiles)

isRunning = "3dsmax.exe" in (i.name() for i in psutil.process_iter())

if (isRunning == False):
    for file in directoryFiles:
        os.startfile(file)
问题原因与解决方法

核心问题

os.listdir(root.directoryPath)返回的只是文件名,而非完整文件路径。当你直接用os.startfile(file)时,程序会在当前脚本的工作目录下去找这个文件,而不是用户选择的目标目录,因此会出现找不到文件的错误。

修复方案

  1. 过滤目标文件:只保留目录中的.max文件,避免处理非目标格式的文件
  2. 拼接完整路径:将用户选择的目录路径与文件名拼接,生成完整的文件路径
  3. 逻辑补全:确保只有在用户选择目录后才执行后续文件操作,避免未选择目录时出现变量未定义的报错

修改后的代码如下:

import os
import psutil
import easygui
import time

from tkinter import filedialog
from tkinter import *

root = Tk()
root.withdraw()  # 隐藏tkinter的主窗口,避免多余界面

msg = "Select a folder to render the .max files inside"
title = "3DS MAX AUTO RENDER"
choice = ["Select Folder"]
reply = easygui.buttonbox(msg, title, choices=choice)

directoryPath = ""
max_files = []

if reply == "Select Folder":
    directoryPath = filedialog.askdirectory(initialdir="/", title="Select a folder")
    print(directoryPath)
    # 过滤出目录中的.max文件并拼接完整路径
    max_files = [os.path.join(directoryPath, f) for f in os.listdir(directoryPath) if f.endswith(".max")]
    print(max_files)

isRunning = "3dsmax.exe" in (i.name() for i in psutil.process_iter())

if not isRunning and max_files:
    for file_path in max_files:
        os.startfile(file_path)

额外优化点

  • 添加root.withdraw()隐藏tkinter默认弹出的空主窗口,提升交互体验
  • 增加max_files非空判断,避免无目标文件时执行无效循环

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 08:45:24