Listing files in a directory not matching pattern

时光总嘲笑我的痴心妄想 提交于 2019-12-07 10:29:13

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!