11.7. :mod:glob — Expansão de padrão de nome de arquivo no estilo Unix¶
Código Fonte: Lib/glob.py
The glob
module finds all the pathnames matching a specified pattern
according to the rules used by the Unix shell, although results are returned in
arbitrary order. No tilde expansion is done, but *
, ?
, and character
ranges expressed with []
will be correctly matched. This is done by using
the os.listdir()
and fnmatch.fnmatch()
functions in concert, and
not by actually invoking a subshell. Note that unlike fnmatch.fnmatch()
,
glob
treats filenames beginning with a dot (.
) as special cases.
(For tilde and shell variable expansion, use os.path.expanduser()
and
os.path.expandvars()
.)
Para uma correspondência literal, coloque os metacaracteres entre colchetes. Por exemplo, '[?]'
corresponde ao caractere '?'
.
Ver também
O módulo pathlib
oferece objetos de caminho de alto nível.
-
glob.
glob
(pathname, *, recursive=False)¶ Return a possibly-empty list of path names that match pathname, which must be a string containing a path specification. pathname can be either absolute (like
/usr/src/Python-1.5/Makefile
) or relative (like../../Tools/*/*.gif
), and can contain shell-style wildcards. Broken symlinks are included in the results (as in the shell).If recursive is true, the pattern “
**
” will match any files and zero or more directories and subdirectories. If the pattern is followed by anos.sep
, only directories and subdirectories match.Nota
Usar o padrão “
**
” em grandes árvores de diretório pode consumir uma quantidade excessiva de tempo.Alterado na versão 3.5: Suporte a globs recursivos usando “
**
”.
-
glob.
iglob
(pathname, recursive=False)¶ Retorna um iterador que produz os mesmos valores que
glob()
sem realmente armazená-los todos simultaneamente.
-
glob.
escape
(pathname)¶ Escapa todos os caracteres especiais (
'?'
,'*'
e'['
). Isso é útil se você deseja corresponder a uma string literal arbitrária que pode conter caracteres especiais. Os caracteres especiais nos pontos de compartilhamento de unidade/UNC não têm escape, por exemplo, no Windowsescape('//?/c:/Quo vadis?.txt')
retorna'//?/c:/Quo vadis[?].txt'
.Novo na versão 3.4.
Por exemplo, considere um diretório contendo os seguintes arquivos: 1.gif
, 2.txt
, card.gif
e um subdiretório sub
que contém apenas o arquivo 3.txt
. glob()
produzirá os seguintes resultados. Observe como todos os componentes principais do caminho são preservados.
>>> import glob
>>> glob.glob('./[0-9].*')
['./1.gif', './2.txt']
>>> glob.glob('*.gif')
['1.gif', 'card.gif']
>>> glob.glob('?.gif')
['1.gif']
>>> glob.glob('**/*.txt', recursive=True)
['2.txt', 'sub/3.txt']
>>> glob.glob('./**/', recursive=True)
['./', './sub/']
Se o diretório contém arquivos começando com .
eles não serão correspondidos por padrão. Por exemplo, considere um diretório contendo card.gif
e .card.gif
>>> import glob
>>> glob.glob('*.gif')
['card.gif']
>>> glob.glob('.c*')
['.card.gif']
Ver também
- Módulo
fnmatch
- Expansão de nome de arquivo no estilo shell (não caminho)