How to Open File Using Python Script in macOS

Hello everyone, in this article, we will learn a pretty useful Python script. We will create a very simple Python code that will open a file on macOS. When we run this script, it will open the file or program that we specified.


import subprocess

program_path = "/Applications/"  # Replace with the path to the program you want to open

# Open the program using the "open" command in MacOS["open", "-a", program_path])

In this code, we first import the “subprocess” module, which allows us to run shell commands from within our Python script. Then, we define the path to the file we want to open in the “file_path” variable. Finally, we use the function to run the “open” command in MacOS with the file path as an argument. This will open the file in its default application on the user’s system.

For example, I am going to open a video file in the Movies folder. The video file name is 2023-02-10 18-02-45.mp4. The code will be like this:

import subprocess

file_path = "/Users/dhani/Movies/2023-02-10 18-02-45.mp4"["open", file_path])

Now let’s run this script.

Thanks for reading this short article on how to open file using python script in macOS.

Be the first to comment

Leave a Reply