0

From Python 3.9 I want to highlight a file in Windows Explorer based on a variable. The below code works fine for a fixed file, e.g.: Y:\picturefile.1234567890.jpg How can I replace this fixed file by a variable so I can let it work for any file from a list?

from tkinter import *
import subprocess


def highlightfile():

    subprocess.run(r'explorer /select,Y:\picturefile.1234567890.jpg')


root = Tk()

# Button to open Windows Explorer and highlight picture file
btn = Button(text="Highlight picture file", command=highlightfile)
btn.pack(side='top')

root.mainloop()

When I replace in the code Y:\picturefile.1234567890.jpg by for instance the variable picturename (containing the same path and file) PyCharm gives an error message: FileNotFoundError: [WinError 2] System cannot find the specified file. So, the below code does NOT work; why not?

from tkinter import *
import subprocess


def highlightfile():
    picturename = "Y:\\picturefile.1234567890.jpg"
    subprocess.run(r'explorer /select, picturename')


root = Tk()

# Button to open Windows Explorer and highlight picture file
btn = Button(text="Highlight picture file", command=highlightfile)
btn.pack(side='top')

root.mainloop()

Many thanks in advance.

Musana
  • 1
  • 2

1 Answers1

0

Finally I solved the question myself. As I have been searching for a long time I show my solution below to help others.

Instead of just replacing the filename I replaced the whole argument of subprocess.run():

def highlightfile():
    run_arg = r'explorer /select, "' + picturename + '"'
    subprocess.run(run_arg)

This works as intended.

Nick
  • 138,499
  • 22
  • 57
  • 95
Musana
  • 1
  • 2
  • This is a good thing to do, you can even accept your own answer (although you won't receive any reputation for doing so). – Nick Apr 12 '22 at 08:22
  • This should work the same without separate variable. Could you add the _broken_ code to your question? – CherryDT Apr 12 '22 at 08:24