I’m in Python, and I have the path of a certain folder. I want to open it using the default folder explorer for that system. For example, if it’s a Windows computer, I want to use Explorer, if it’s Linux, I want to use Nautilus or whatever is the default there, if it’s Mac, I want to use Finder.

How can I do that?

I am surprised no one has mentioned using xdg-open for *nix which will work for both files and folders:

import os
import platform
import subprocess

def open_file(path):
    if platform.system() == "Windows":
        os.startfile(path)
    elif platform.system() == "Darwin":
        subprocess.Popen(["open", path])
    else:
        subprocess.Popen(["xdg-open", path])

You can use subprocess.

import subprocess
import sys

if sys.platform == 'darwin':
    def openFolder(path):
        subprocess.check_call(['open', '--', path])
elif sys.platform == 'linux2':
    def openFolder(path):
        subprocess.check_call(['xdg-open', '--', path])
elif sys.platform == 'win32':
    def openFolder(path):
        subprocess.check_call(['explorer', path])

The following works on Macintosh.

import webbrowser
webbrowser.open('file:///Users/test/test_folder')

On GNU/Linux, use the absolute path of the folder. (Make sure the folder exists)

import webbrowser
webbrowser.open('/home/test/test_folder')

As pointed out in the other answer, it works on Windows, too.

I think you may have to detect the operating system, and then launch the relevant file explorer accordingly.

This could come in userful for OSX’s Finder: Python “show in finder”

(The below only works for windows unfortunately)

import webbrowser as wb
wb.open('C:/path/to/folder')

This works on Windows. I assume it would work across other platforms. Can anyone confirm? Confirmed windows only 🙁

One approach to something like this is maybe to prioritize readability, and prepare the code in such a manner that extracting abstractions is easy. You could take advantage of python higher order functions capabilities and go along these lines, throwing an exception if the proper function assignment cannot be made when a specific platform is not supported.

import subprocess
import sys


class UnsupportedPlatformException(Exception):
    pass


def _show_file_darwin():
    subprocess.check_call(["open", "--", path])

def _show_file_linux():
    subprocess.check_call(["xdg-open", "--", path])

def _show_file_win32():
    subprocess.check_call(["explorer", "/select", path])

_show_file_func = {'darwin': _show_file_darwin, 
                   'linux': _show_file_linux,
                   'win32': _show_file_win32}

try:
    show_file = _show_file_func[sys.platform]
except KeyError:
    raise UnsupportedPlatformException


# then call show_file() as usual