Search code examples
pythonglob

Listing files in a directory not matching pattern


The following code lists down all the files in a directory beginning with "hello":

import glob
files = glob.glob("hello*.txt")

How can I select other files that ARE NOT beginning with "hello"?


Solution

  • According to glob module's documentation, it works by using the os.listdir() and fnmatch.fnmatch() functions in concert, and not by actually invoking a subshell.

    os.listdir() returns you a list of entries in the specified directory, and fnmatch.fnmatch() provides you with unix shell-style wildcards, use it:

    import fnmatch
    import os
    
    for file in os.listdir('.'):
        if not fnmatch.fnmatch(file, 'hello*.txt'):
            print file
    

    Hope that helps.