'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?



Solution 1:[1]

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))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1