102

In Python, how do I jump to a file in the Windows Explorer? I found a solution for jumping to folders:

import subprocess
subprocess.Popen('explorer "C:\path\of\folder"')

but I have no solution for files.

NoDataDumpNoContribution
  • 10,591
  • 9
  • 64
  • 104
Kirill Titov
  • 2,060
  • 5
  • 21
  • 33

11 Answers11

118

From Geoff Chappell's The Windows Explorer Command Line

import subprocess
subprocess.Popen(r'explorer /select,"C:\path\of\folder\file"')
Blair Conrad
  • 233,004
  • 25
  • 132
  • 111
  • I'm aware that this is a super old post but it's worth a shot. I have a module that connects a sharepoint document library to a Windows Explorer window so that a copy past locally will upload to the sharepoint doc library. This occasionally needs to be refreshed and I'm using selenium to reconnect but now I've got an open Windows Explorer window. I'm clueless how to close that window so that the application GUI becomes the focus for the end user again. Any idea how to select that window and close it? – Benjooster Sep 26 '13 at 12:53
  • haha, I was reading the comma as a string adder, i was like WTF is going on. It's part of the string. – shawn Jan 16 '14 at 01:08
  • 26
    For some odd reason, on my windows 10 system, this just opens up the explorer user libraries with 'My Documents' in focus. – MisterGeeky Nov 14 '15 at 19:47
  • `subprocess.Popen(r'explorer /select,"C:\path\of\folder\file"')` works, but how do I get this window on top of other windows, if the user goes to some other window after having executed this statement somewhere in his program? – Nancy Jan 21 '16 at 06:13
  • @Nik It's like a year late, but I think the reason that happens is because your filepath isn't pointing to a specific file. It seems you can't just point to a directory. – nickvans Nov 11 '16 at 00:10
  • A working link (as of now) to command-line options: http://www.geoffchappell.com/studies/windows/shell/explorer/cmdline.htm – AGN Gazer Jun 07 '18 at 05:56
  • Using this method will give me a return code of `1` even though the explorer window opens correctly and selects the file. Does anyone know why this is, maybe worth a question in its self? (I get a return code of `1` if I use the string command with `os.system`, `subprocess.call`, or subprocess.Popen and ask for the return code.) – Philip Scadding Sep 19 '18 at 14:16
  • 4
    I'm having the same issue as @MisterGeeky, it just opens "My Documents". I'm pretty sure it has something to do with the backslashes... – birgersp Sep 03 '19 at 09:37
  • 1
    I forgot to add the `comma (,)` between `/select` and the `path` then the `My Documents` is opened. i.e. `explorer /select,"C:\path\of\folder\file"` is correct not this `explorer /select "C:\path\of\folder\file"` – Phani Rithvij Dec 25 '19 at 08:01
  • A good resource for explorer CMD options: https://ss64.com/nt/explorer.html – Elijah Mar 14 '20 at 15:47
  • 4
    if you're using forward slashes in the filepath then do a filepath.replace('/', '\\') so that it's like C:\path\of\folder\file – Paul Sumpner Apr 14 '20 at 04:58
  • What's the comma after select for? – theonlygusti Nov 03 '21 at 02:51
  • If you're converting slashes like @PaulSumpner suggests, remember to use a raw string so you don't get double slashes (which is extremely annoying that that isn't automatically handled...) – Spencer Jan 21 '22 at 22:15
  • 1
    Saw that if you want to combine f and r strings for performing this its doable to do `subprocess.Popen(fr'explorer /select,"{my_var}"')` – Ola Karlsson Dec 22 '22 at 15:23
37

A nicer and safer solution (only in Windows unfortunately) is os.startfile().

When it's given a folder instead of a file, it will open Explorer.

Im aware that i do not completely answer the question since its not selecting a file, but using subprocess is always kind of a bad idea (for security reasons) and this solution may help other people.

Guillaume Lebreton
  • 2,586
  • 16
  • 25
  • Yes, sure, I get the idea of insecurity, but I was very safe :) Thx for your tip though, that helped me too (yes, through the years) – Kirill Titov Mar 14 '18 at 21:52
  • 2
    Not very cross OS, `startfile` only exists on Windows (https://stackoverflow.com/questions/29823028/attributeerror-module-object-has-no-attribute-startfile). – c z May 10 '18 at 15:53
  • 1
    Another bummer: `os.startfile()` does not accept arguments ☹ Although in case of the Explorer it seems easy to have the process detached via `subprocess.run` or `Popen` – ewerybody Jun 21 '18 at 09:38
  • 2
    This function reject path like `./some/folder`. you may use `os.path.abspath("./some/folder")` to convert the path first. – tsh Jun 30 '21 at 03:44
  • 2
    "Using subprocess is always kind of a bad idea" ... what? No, it isn't. – Glenn Maynard Nov 17 '21 at 08:15
  • @GlennMaynard Because for example, `cmd=r'explorer /select,"C:\path\of\folder\file"'; subprocess.Popen(cmd)` if the string cmd is compromised by an evil user it can for example create a new file (example on window): `'cmd /c type NUL > 1.txt'`. With more imagination there is a lot of evil things to do, and that's why i think playing with subprocess is not a good idea. – Guillaume Lebreton Nov 21 '21 at 14:34
16

As explorer could be overridden it would be a little safer to point to the executable directly. (just had to be schooled on this too)

And while you're at it: use Python 3s current subprocess API: run()

import os
import subprocess
FILEBROWSER_PATH = os.path.join(os.getenv('WINDIR'), 'explorer.exe')

def explore(path):
    # explorer would choke on forward slashes
    path = os.path.normpath(path)

    if os.path.isdir(path):
        subprocess.run([FILEBROWSER_PATH, path])
    elif os.path.isfile(path):
        subprocess.run([FILEBROWSER_PATH, '/select,', path])
ewerybody
  • 1,443
  • 16
  • 29
11

For some reason, on windows 7 it always opens the users Path, for me following worked out:

import subprocess
subprocess.call("explorer C:\\temp\\yourpath", shell=True)
user1767754
  • 23,311
  • 18
  • 141
  • 164
  • 1
    `subprocess.Popen(r'explorer /select,"C:\path\of\folder\file"')` works, but how do I get this window on top of other windows, if the user goes to some other window after having executed this statement somewhere in his program? – Nancy Jan 21 '16 at 06:14
  • This should automatically pop at the front – user1767754 Jan 23 '16 at 21:48
  • Try to avoid use of `shell=True` tho! https://security.openstack.org/guidelines/dg_use-subprocess-securely.html – ewerybody Jun 21 '18 at 09:40
  • As long as you know where you are using and it's in a closed environment, that's fine – user1767754 Jun 21 '18 at 17:30
11

Alternatively, you could use the fileopenbox module of EasyGUI to open the file explorer for the user to click through and then select a file (returning the full filepath).

import easygui
file = easygui.fileopenbox()
MacNutter
  • 182
  • 1
  • 5
8

For anyone wondering how to use a variable in place of a direct file path. The code below will open explorer and highlight the file specified.

import subprocess
subprocess.Popen(f'explorer /select,{variableHere}')

The code below will just open the specified folder in explorer without highlighting any specific file.

import subprocess
subprocess.Popen(f'explorer "{variableHere}"')

Ive only tested on windows

Stephan Yazvinski
  • 484
  • 1
  • 6
  • 12
  • In python 3 this should be a raw format string, i.e. `subprocess.Popen(fr'explorer "{variableHere}"')` – Spencer Jan 21 '22 at 22:16
1

Code To Open Folder In Explorer:

import os
import ctypes
SW_SHOWDEFAULT = 10
path_to_open = os.getenv('windir')
ctypes.windll.shell32.ShellExecuteW(0, "open", path_to_open, 0, 0, SW_SHOWDEFAULT)
Pixelsuft
  • 97
  • 5
0
import subprocess
subprocess.Popen(r'explorer /open,"C:\path\of\folder\file"')

I find that the explorer /open command will list the files in the directory. When I used the /select command (as shown above), explorer opened the parent directory and had my directory highlighted.

RAllenAZ
  • 36
  • 4
0
import os
os.system('notepad filename')

Example 1. If I have a file no.txt in same directory

os.system('notepad no.txt')

Example 2. If I want to open file in some other directory

os.system('notepad "C:\\Users\\DELL\\Downloads\\a.txt"')

Note: I am running this on windows thats why I am using notepad, you can replace according to your os.

0
import os 
path = "C:\path\of\folder"
os.startfile(path)

using this cmd you can go to the path in the file explorer

0

This is not entirely an answer to the question, but it helped me so I thought it might help others too.

If you use are using wxPython/wxWidgets, you can try the wx.LaunchDefaultApplication and wx.LaunchDefaultBrowser methods. I'm not sure how they behave on Windows, but on my Linux setup they both open my default file manager if I provide a local path that points to a directory as the document or url parameter, respectively.

Newbyte
  • 2,421
  • 5
  • 22
  • 45