os.startfile() don't open the file - python

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:"
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)

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.

Related

Python File Moving Problems

i'm trying to code a patch programs with python to move translation files into the game.
i was able to make a program to select the file, but i'm suffering to move that selected file to the designated destination.
it says that python could not find the file "files", but i couldnt find the solution how to make it read the file.
import shutil
import os
from tkinter import filedialog
from tkinter import messagebox
list_file = []
files = filedialog.askopenfilenames(initialdir="/",\
title = "Select file")
if files == '':
messagebox.showwarning("Warning", "Add the file.")
destination = r'C:\Program Files (x86)\Steam\steamapps\common\I Wanna Maker\locale'
shutil.move("files", "destination")

File identified but cannot be deleted - Python

So I'm trying to make the a program that deletes files which can be launched from the command lines. But when I run it, it fails and returns the following message: FileNotFoundError: [WinError 2] The system cannot find the file specified: 'test.txt'. Here's the code:
import sys
import os
num = int(sys.argv[1])
files = os.listdir(sys.argv[2])
for file in files[:num]:
print('Deleting '+file+'...')
os.remove(file)
The file is identified but it cannot be deleted.
You need to add the directory path back to the path:
import sys
import os
num = int(sys.argv[1])
files = os.listdir(sys.argv[2])
for file in files[:num]:
print('Deleting '+file+'...')
os.remove(os.path.join(sys.argv[2], file))
os.listdir will only return the basename of the file, whereas you'll need a relative or full path

How to get the desktop path of the original non-admin user when running a python file as admin

I am trying to use win32com to create a shortcut to my user's desktop. When I use the code below, I am calling os.environ['USERPROFILE'] with join to Desktop or winshell.desktop() to get the path to the user's desktop. However, since this needs to be ran as an admin, it is only grabbing the admin's desktop path and not the intended user's. Is there a way to get the actual logged-in user's desktop path when running a python script as an admin?
This is the entire code. The line in part in question is the second try statement.
import pathlib
import os, winshell
import os.path
from os import path
from win32com.client import Dispatch
import zipfile
import ctypes
def Mbox(title, text, style):
return ctypes.windll.user32.MessageBoxW(0, text, title, style)
def install():
try:
if(os.path.exists(r"C:\Program Files\Report Builder")):
Mbox('Error','That file already exists.',0)
raise Exception('Error','That file already exists.')
else:
with zipfile.ZipFile(r"{}".format(str(pathlib.Path().absolute())+"\Report Builder.zip"), 'r') as zip_ref:
zip_ref.extractall(r"C:\Program Files")
except (Exception) as error:
Mbox('Error',str(error),0)
else:
try:
desktop = os.path.join(os.environ['USERPROFILE'],'Desktop')
path = os.path.join(desktop, "Report Builder.lnk")
target = r"C:\Program Files\Report Builder\dist\reportbuilder\reportbuilder.exe"
wDir = r"C:\Program Files\Report Builder\dist\reportbuilder"
icon = r"C:\Program Files\Report Builder\dist\reportbuilder\rbpuzz.ico"
shell = Dispatch('WScript.Shell')
shortcut = shell.CreateShortCut(path)
shortcut.Targetpath = target
shortcut.WorkingDirectory = wDir
shortcut.IconLocation = icon
shortcut.save()
except (Exception) as error:
Mbox('Error',str(error),0)
else:
Mbox('Success!','A shortcut has been added to your desktop.',0)
if __name__ == "__main__":
install()

how to check if a file exists and create one if it's missing, while the path to the file is incomplete as below

I have to create a empty text file called file.txt under this path
/home/project/test*/today/file.txt
test* changes each time like test_product or test_1 etc..
I tried the following code:
if(os.path.exists("/home/project/test*/today/file.txt"):
print "Found"
else:
open("/home/project/test*/today/file.txt",a).close()```
I got this error
```IOError: [Errno 2] No such file or directory: '/home/project/test*/today/file.txt'```
I understand I can use glob to search the files with paths like * , but I am unable to figure out how to create a file while having * in the path.
Your code logically doesn't make any sense. What you're basically saying is
if the file exists: display the text Found
otherwise the file does not exist, so try to open the file that does not exist
I'll tell you why it doesn't work. os module does not support wildcards.
If you wanted to use wildcards * you could use glob.
import glob
import os
from pathlib import Path
def check_for_files(filepath):
for filepath_object in glob.glob(filepath):
if os.path.isfile(filepath_object):
return True
return False
file_to_check = "/home/project/test*/today/file.txt"
if not (check_for_files(file_to_check):
Path(file_to_check).touch()

Beginner:Python 3.66. Win7. How do I ignore sub-folders in this code?

Can anyone tell me how I can get the for loop at the end of this program
NOT to rename folders, only files? I'm at a loss on this one.
I'm assuming the command to use is if os.path.isdir(file)
but I cant seem to get it to work no matter where I put it, same goes for os.path.isfile().
I'm still at the stage (my first week) where I am confused by most commands and functions, though I did dabble in ZX BASIC\AMOS and STOS in the 80s\90s so I have a rudimentary understanding of variables etc.
#FRenum-v.05
#renumbers a folder of files 01 onward preserving file extensions.
#steve Shambles. june 2018, my 2nd ever python program
from tkinter import filedialog
from tkinter import *
import os
import os.path
import subprocess
#user selects directory
root = Tk()
root.withdraw() #stop tk window opening
folder_selected = filedialog.askdirectory() #open file requestor
#change dir to folder selected by user,
os.chdir (folder_selected)
# read user selected dir
files = os.listdir(folder_selected)
# inc is counter to keep track of what file we are working on
inc = 1
for file in files:
#store file extension in string file_ext
file_ext = os.path.splitext(file)[1]
# build new filename, starting with a "0"
#then value of inc then add file ext
created_file=("0"+str(inc)+ file_ext)
#if filename does not already exist then rename it
if not os.path.exists(created_file):
os.rename(file,created_file)
#next one please, until done
inc = inc+1 #add to counter
#Display contents of folder in explorer
#https://stackoverflow.com/questions/50892257/beginner-opening-explorer-to- show-folder-contents
subprocess.Popen(["C:\\Windows\\explorer.exe", folder_selected.replace('/', '\\')])
#thanks to Michael for this line if code
load the modules can add it at the beginning of the script
from os.path import join , isfile
add this line before the loop:
files = [filenames for filenames in files if isfile(join(folder_selected, filenames))]

Categories

Resources