Emmanuel Goldstein
Emmanuel Goldstein

Reputation: 363

Python: how to open folder of a file and point to it

At the end of my python script I want to open the folder (location) of a generated file (not the file itself) and have the cursor point at it (similar to when showing a file in a folder in Finder):

The generated file path is in the variable output_path, but when I do this:

os.system("open " + output_path)

The file, and not the location, opens. How to modify it so it does what I aim to do?

Upvotes: 0

Views: 190

Answers (1)

Barmar
Barmar

Reputation: 782498

Use os.path.dirname() to get the directory name from a pathname. Also, use shlex.quote() to escape any special characters before using this with os.system().

import shlex
import os

os.system("open " + shlex.quote(os.path.dirname(output_path))

Upvotes: 1

Related Questions