1. Home
  2. Computing & Technology
  3. Python
Python Blog

From Al Lukaszewski, for About.com

Globbing a Group of Hits

Thursday March 27, 2008
For reasons of security and the smooth-running of your program, it is a good idea to check whether an executable exists before you call it. There are two ways to do this in Python.

The glob module allows you to retrieve a listing of the current working directory and to return hits according to regular expressions. It has two methods, glob and iglob. The first returns a fixed set à la range(), while the second returns an iterator that saves on system resources. Both are called the same way:
import glob
listing = glob.glob('*.txt')
This will return a list of all text files. To check for a particular executable, simply insert the file name as the argument, and frame it in an if loop:
if glob.glob('MyExecutable.exe'): existence = 1
A second way to check for a file's existence is to use the exists() method of os.path. Recall that we used the os module previously to get our current working directory. os.path is a subset of os that is available when you import os.
import os
existence = os.path.exists('MyExecutable.exe')
The exists() method returns True if the file exists and False if it does not.
Explore Python
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. Python

©2009 About.com, a part of The New York Times Company.

All rights reserved.