【问题标题】:Listing files in a directory not matching pattern列出与模式不匹配的目录中的文件
【发布时间】:2014-05-02 18:24:09
【问题描述】:

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

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

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

【问题讨论】:

    标签: python glob


    【解决方案1】:

    只使用 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']
    >>>
    

    【讨论】:

    • glob('[!hello]*') 将丢弃的不仅仅是以"hello" 开头的名称。来自docs[!seq] 匹配任何不在seq 中的字符
    【解决方案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
    

    希望对您有所帮助。

    【讨论】:

      【解决方案3】:

      您可以使用 "*" 模式简单地匹配 所有 文件,然后清除您不感兴趣的文件,例如:

      from glob import glob
      from fnmatch import fnmatch
      
      files = [f for f in glob("*") if not fnmatch(f, "hello*.txt")]
      

      【讨论】:

        猜你喜欢
        • 2012-01-21
        • 2011-01-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-10-13
        • 2020-01-23
        相关资源
        最近更新 更多