【发布时间】:2014-05-02 18:24:09
【问题描述】:
以下代码列出了以"hello"开头的目录中的所有文件:
import glob
files = glob.glob("hello*.txt")
如何选择其他不以"hello" 开头的文件?
【问题讨论】:
以下代码列出了以"hello"开头的目录中的所有文件:
import glob
files = glob.glob("hello*.txt")
如何选择其他不以"hello" 开头的文件?
【问题讨论】:
只使用 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 中的字符
根据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
希望对您有所帮助。
【讨论】:
您可以使用 "*" 模式简单地匹配 所有 文件,然后清除您不感兴趣的文件,例如:
from glob import glob
from fnmatch import fnmatch
files = [f for f in glob("*") if not fnmatch(f, "hello*.txt")]
【讨论】: