Novice Novice - 1 year ago 89
Python Question

How to open current working directory (OS X/Linux/Win)

Is there a way to open the current working directory in python?

current_wkd = os.getcwd()

Say at the end of my program, I want to open the current working directory. I know how to open specific files, but I am interested in the "/User/Bob/folder" opening once the program is complete. How to open "folder" at the end of the script?

What is the best way to do this in OSX/Linux/Win.

Thank you.

For example,

In the terminal one can use:

pwd # get current wkd
cd /User/Bob/folder # change directory to /User/Bob/folder
open folder # To open the directory named "folder"

Is this possible as part of the python script. At the end, for the directory to open as in the above "open folder" command in the terminal. I know how to find the current wkd and change it using:


How do you open the current directory? In other words, at the end of my script I want the directory/folder to open. Similarly to when opening a web browser using:


Thank you e9T (below) for the guidance!

ANSWER: I ended up using this as part of my script at the end:

import subprocess

current_directory = os.getcwd()

subprocess.check_call(['open', '--', current_directory]) # This is for OS X

e9t e9t
Answer Source

You can use subprocess to open up a file explorer for a given path.

import subprocess
import sys

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

open_folder(path=".")  # open current directory
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download