列出不匹配模式的目录文件
下面的代码会列出一个文件夹中所有以 "hello"
开头的文件:
import glob
files = glob.glob("hello*.txt")
我该怎么做才能选择那些不以 "hello"
开头的文件呢?
3 个回答
0
你可以用 "*"
这个模式来匹配 所有 文件,然后再把你不想要的文件筛选掉,比如:
from glob import glob
from fnmatch import fnmatch
files = [f for f in glob("*") if not fnmatch(f, "hello*.txt")]
8
只用 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']
>>>
2
根据glob
模块的文档,它的工作原理是结合使用os.listdir()
和fnmatch.fnmatch()
这两个函数,而不是通过实际调用一个子命令行。
os.listdir()
会给你返回指定目录下的所有文件和文件夹的列表,而fnmatch.fnmatch()
则提供了类似于Unix命令行的通配符,可以用来匹配文件名,使用方法如下:
import fnmatch
import os
for file in os.listdir('.'):
if not fnmatch.fnmatch(file, 'hello*.txt'):
print file
希望这对你有帮助。