问题
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"
?
回答1:
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.
回答2:
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']
>>>
回答3:
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")]
来源:https://stackoverflow.com/questions/22625616/listing-files-in-a-directory-not-matching-pattern