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

4 python glob

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

import glob
files = glob.glob("hello*.txt")
Run Code Online (Sandbox Code Playgroud)

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

Jam*_*pam 7

如何仅使用glob:

匹配所有文件:

>>> glob.glob('*')
['fee.py', 'foo.py', 'hello.txt', 'hello1.txt', 'test.txt', 'text.txt']
>>>
Run Code Online (Sandbox Code Playgroud)

仅匹配hello.txt:

>>> glob.glob('hello*.txt')
['hello.txt', 'hello1.txt']
>>>
Run Code Online (Sandbox Code Playgroud)

没有字符串匹配hello:

>>> glob.glob('[!hello]*')
['fee.py', 'foo.py', 'test.txt', 'text.txt']
>>>
Run Code Online (Sandbox Code Playgroud)

匹配没有字符串hello但结尾为.txt:

>>> glob.glob('[!hello]*.txt')
['test.txt', 'text.txt']
>>>
Run Code Online (Sandbox Code Playgroud)


ale*_*cxe 2

根据glob模块的文档,它通过协同使用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
Run Code Online (Sandbox Code Playgroud)

希望有帮助。