next up previous contents
Next: Information about your Python Up: Using Modules Previous: Operating System Services: os   Contents

Expansion of Filename wildcards - the glob module

Under the UNIX operating system, when a filename contains certain symbols, the command shell expands these symbols to represent a list of files that match a specified pattern. For example, if a file name of *.c is passed to the UNIX shell, it will expand the name to represent all of the files in the current directory which end with ``.c''. In some applications, it would be useful to be able to perform this expansion inside your program, without the need to invoke a shell. The glob module provides the glob function which accepts a filename wildcard expression, and returns a list with the names of all the files which match the expression. One example of glob's use would be to perform filename expansion on the command line for a program designed to run under Windows. A second example would be to find all of the files that begin with a particular string and change that part of the filename to some other string. The wildcard characters which are supported are *, which represents zero or more of any character, ?, which represents exactly one occurence of any character, and a list of characters contained within square brackets ([ ]), which defines a character class similar to the character classes in the re module (Section 8.5). Here's one way to solve the renaming problem, assuming that the old and new strings are passed as the first and second command line arguments, respectively:
import sys,glob,re,os

(old,new) = sys.argv[1:3]

oldre = re.compile(old)

changefiles = glob.glob(old + '*')
for c in changefiles:
        os.rename(c,oldre.sub(new,c,count=1))
(Reading command line arguments is covered in more detail in Section 8.8.)

Keep in mind that under Windows, the glob function is case insensitive, while under UNIX it is not.


next up previous contents
Next: Information about your Python Up: Using Modules Previous: Operating System Services: os   Contents
Phil Spector 2003-11-12