os.startfile() don't open the file

Question:

I want to make a list of files .max from a directory that the user can choose and then open it when the 3ds Max is not running.

The problem is that I am using os.starfile() to open the .max file and even tryied to use subprocess but none of them works and the following message appears:

  • "FileNotFoundError: [WinError 2] the system cannot find the file specified:"

enter image description here

As you can you see, the program recognizes the path of the directory and the files .max that are inside of it.

I’ve already used os.startfile to open a .max file once and it did it works, but can’t figure it out why it’s not working this time.

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)
Asked By: Lucas Costanski

||

Answers:

The file names returned by os.listdir are relative to the directory given. As you are not in that directory when you run the script it can’t find the file which is why you get an error.

Use os.path.join to join the directory and file name:

directoryFiles = [os.path.join(root.directoryPath, x) for x in os.listdir(root.directoryPath)]

directoryFiles will then contain the absolute paths so you won’t get the error.

Answered By: Henry
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.