Question

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"?

Was it helpful?

Solution 2

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.

OTHER TIPS

How about using glob only:

Match all the files:

>>> glob.glob('*')
['fee.py', 'foo.py', 'hello.txt', 'hello1.txt', 'test.txt', 'text.txt']
>>>

Match only hello.txt:

>>> glob.glob('hello*.txt')
['hello.txt', 'hello1.txt']
>>>

Match without string hello:

>>> glob.glob('[!hello]*')
['fee.py', 'foo.py', 'test.txt', 'text.txt']
>>>

Match without string hello but ending with .txt:

>>> glob.glob('[!hello]*.txt')
['test.txt', 'text.txt']
>>>

You could simply match all files using the "*" pattern, then weed out the ones you're not interested in, e.g.:

from glob import glob
from fnmatch import fnmatch

files = [f for f in glob("*") if not fnmatch(f, "hello*.txt")]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top