How can I open files in external programs in Python?

On Windows you could use os.startfile() to open a file using default application:

import os
os.startfile(filename)

There is no shutil.open() that would do it cross-platform. The close approximation is webbrowser.open():

import webbrowser
webbrowser.open(filename)

that might use automatically open command on OS X, os.startfile() on Windows, xdg-open or similar on Linux.

If you want to run a specific application then you could use subprocess module e.g., Popen() allows to start a program without waiting for it to complete:

import subprocess

p = subprocess.Popen(["notepad.exe", fileName])
# ... do other things while notepad is running
returncode = p.wait() # wait for notepad to exit

There are many ways to use the subprocess module to run programs e.g., subprocess.check_call(command) blocks until the command finishes and raises an exception if the command finishes with a nonzero exit code.


Use this to open any file with the default program:

import os
def openFile():
    fileName = listbox_1.get(ACTIVE)
    os.system("start " + fileName)

If you really want to use a certain program, such as notepad, you can do it like this:

import os
def openFile():
    fileName = listbox_1.get(ACTIVE)
    os.system("notepad.exe " + fileName)

Also if you need some if checks before opening the file, feel free to add them. This only shows you how to open the file.

Tags:

Python