Rich
Rich

Reputation: 12663

Open File Explorer in Python, or focus if already open and in same directory

In Python I'd like to open a file explorer to a specific directory, or if it is already open in another window, bring focus to that window. Currently I'm doing this:

os.startfile(path, 'explore')

But it opens as many File Explorers as calls to os.startfile. Is it possible in Python to focus on an existing one?

Upvotes: 4

Views: 4990

Answers (2)

Arthur Lee
Arthur Lee

Reputation: 10

For Python3 (Works for Mac and PC):

import platform


def showFileExplorer(file):  # Path to file (string)
    if platform.system() == "Windows":
        import os
        os.startfile(file)
    elif platform.system() == "Darwin":
        import subprocess
        subprocess.call(["open", "-R", file])
    else:
        import subprocess
        subprocess.Popen(["xdg-open", file])

showFileExplorer(os.path.abspath(file)) 

`

Upvotes: 0

Juan Carlos Asuncion
Juan Carlos Asuncion

Reputation: 136

Stumbled upon this question looking for the exact opposite of what you want, to open the explorer multiple times on the same directory.

Coming from the documentation

os.startfile

When operation is not specified or 'open', this acts like double-clicking the file in Windows Explorer, or giving the file name as an argument to the start command from the interactive command shell: the file is opened with whatever application (if any) its extension is associated.

so just doing

os.startfile(path)

or

os.startfile(path, 'open')

would do exactly what you want as long as the opened explorer is still in the directory you started with. I don't know if I am correct though as my answer assumes you are on win7 os and using python 2.7.

Upvotes: 1

Related Questions