简体   繁体   中英

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()
print(current_wkd) 
.../User/Bob/folder 

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
../User/Bob/folder  
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:

os.getcwd()
os.chdir()

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:

webbrowser.open_new()

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 

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM