在不匹配模式的目录中列出文件

时间:2014-03-25 04:44:22

标签: python glob

以下代码列出了以"hello"开头的目录中的所有文件:

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

如何选择不以"hello"开头的其他文件?

3 个答案:

答案 0 :(得分:7)

如何仅使用glob:

匹配所有文件:

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

仅匹配hello.txt

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

不使用字符串hello进行匹配:

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

不使用字符串hello进行匹配,但以.txt结尾:

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

答案 1 :(得分:2)

根据glob模块的documentation,它可以通过协同使用os.listdir()fnmatch.fnmatch()函数来工作,而不是通过实际调用子shell。

os.listdir()返回指定目录中的条目列表,fnmatch.fnmatch()为您提供unix shell样式的通配符,使用它:

import fnmatch
import os

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

希望有所帮助。

答案 2 :(得分:0)

您只需使用"*"模式匹配所有文件,然后清除您不感兴趣的文件,例如:

from glob import glob
from fnmatch import fnmatch

files = [f for f in glob("*") if not fnmatch(f, "hello*.txt")]
相关问题