Python os.startfile() Method

The os.startfile() method is used in Python to open a file with an associated application, similar to double-clicking the file in Windows Explorer. This method is specific to the Windows platform.

This method can open documents, play media files, or launch applications based on file types and their associated programs on the system.

The os.startfile() method works only on Windows. It will raise an AttributeError if used in other operating systems like Linux or macOS.

Unlike subprocess calls, this method doesn’t allow interaction with the opened application. It’s simply a way to launch an application or file.

Syntax

os.startfile(path, operation=None)

Parameters

Name Description
path (string) It is the path to the file or the program you want to open.
operation (string, optional) The action to be performed on the file. The default operation is None, which means open.

Return value

This method does not return any value. It simply triggers the opening of the file with the associated program.

Example 1: Opening a text file

We will open this file:

Screenshot of Sample text file

import os

# Opens a text file in the default text editor
os.startfile("data.txt")

Output

Output of os.startfile() method in Python

If we run this code on macOS, you will get this error:

AttributeError: module 'os' has no attribute 'startfile'

Example 2: Printing a document

import os

# The 'print' operation might open a print dialog or 
# send the file directly to the default printer
os.startfile("Rplots.pdf", "print")

Output

Output of printing a document

Example 3: Handling errors

import os

try:
  os.startfile("nonexistent_file.txt")
except FileNotFoundError as error:
  print(f"Error: {error}")
except Exception as e:
  print(f"An error occurred: {e}")

Output

FileNotFoundError: [Errno 2] No such file or directory: 'nonexistent_file.txt'

That’s all!

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.