glob — Expansión del patrón de nombres de ruta de estilo Unix

Código fuente: Lib/glob.py


El módulo glob encuentra todos los nombres de rutas que se asemejan a un patrón especificado de acuerdo a las reglas que se siguen en una terminal Unix, aunque los resultados se retornan con un orden arbitrario. No se realiza expansión de virgulilla (tilde («~») expansion en inglés) pero *, ? y caracteres de rango expresados mediante [] serán emparejados correctamente. Esto se realiza usando las funciones os.scandir() y fnmatch.fnmatch() de forma concertada sin invocar, realmente, a una subshell.

Nótese que, los archivos que comienzan con un punto (.) solo se puede combinar con patrones que también comiencen con un punto, a diferencia de fnmatch.fnmatch(), o pathlib.Path.glob(). (Para la expansión de virgulilla o variable de terminal, use os.path.expanduser() y os.path.expandvars().)

Para una coincidencia literal, envuelve los meta-caracteres en corchetes. Por ejemplo, '[?]' empareja el caracter '?'.

The glob module defines the following functions:

glob.glob(pathname, *, root_dir=None, dir_fd=None, recursive=False, include_hidden=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). Whether or not the results are sorted depends on the file system. If a file that satisfies conditions is removed or added during the call of this function, whether a path name for that file will be included is unspecified.

Si root_dir no es None, debería ser un path-like object que especifique el directorio raíz para la búsqueda. Tiene el mismo efecto en glob() que cambiar el directorio actual antes de llamarlo. Si pathname es relativo, el resultado contendrá rutas relativas a root_dir.

Esta función puede admitir rutas relativas a descriptores de directorio con el parámetro dir_fd.

Si recursive es verdadero, el patrón «**» coincidirá con cualquier fichero y cero o más directorios, subdirectorios y enlaces simbólicos a directorios. Si el patrón va seguido de un os.sep o os.altsep los ficheros no coincidirán.

Si include_hidden es verdadero, el patrón «**» coincidirá con los directorios ocultos.

Lanza un evento de auditoría glob.glob con los argumentos pathname, recursive.

Lanza un auditing event glob.glob/2 con argumentos pathname, recursive, root_dir, dir_fd.

Nota

El uso del patrón «**» en árboles de directorios grandes podría consumir una cantidad de tiempo excesiva.

Nota

This function may return duplicate path names if pathname contains multiple «**» patterns and recursive is true.

Distinto en la versión 3.5: Soporte para globs recursivos usando «**».

Distinto en la versión 3.10: Se agregaron los parámetros root_dir y dir_fd.

Distinto en la versión 3.11: Agregado el parámetro include_hidden.

glob.iglob(pathname, *, root_dir=None, dir_fd=None, recursive=False, include_hidden=False)

Retorna un iterador el cual produce los mismos valores que glob() sin necesidad de almacenarlos todos de forma simultánea.

Lanza un evento de auditoría glob.glob con los argumentos pathname, recursive.

Lanza un auditing event glob.glob/2 con argumentos pathname, recursive, root_dir, dir_fd.

Nota

This function may return duplicate path names if pathname contains multiple «**» patterns and recursive is true.

Distinto en la versión 3.5: Soporte para globs recursivos usando «**».

Distinto en la versión 3.10: Se agregaron los parámetros root_dir y dir_fd.

Distinto en la versión 3.11: Agregado el parámetro include_hidden.

glob.escape(pathname)

Escapa todos los caracteres especiales ('?', '*' y '['). Esto es útil si deseas coincidir una cadena de caracteres literal arbitraria que podría contener caracteres especiales. Los caracteres especiales en unidades compartidas/UNC no se eluden, e.g. en Windows escape('//?/c:/Quo vadis?.txt') retorna '//?/c:/Quo vadis[?].txt'.

Nuevo en la versión 3.4.

glob.translate(pathname, *, recursive=False, include_hidden=False, seps=None)

Convert the given path specification to a regular expression for use with re.match(). The path specification can contain shell-style wildcards.

For example:

>>> import glob, re
>>>
>>> regex = glob.translate('**/*.txt', recursive=True, include_hidden=True)
>>> regex
'(?s:(?:.+/)?[^/]*\\.txt)\\Z'
>>> reobj = re.compile(regex)
>>> reobj.match('foo/bar/baz.txt')
<re.Match object; span=(0, 15), match='foo/bar/baz.txt'>

Path separators and segments are meaningful to this function, unlike fnmatch.translate(). By default wildcards do not match path separators, and * pattern segments match precisely one path segment.

If recursive is true, the pattern segment «**» will match any number of path segments.

If include_hidden is true, wildcards can match path segments that start with a dot (.).

A sequence of path separators may be supplied to the seps argument. If not given, os.sep and altsep (if available) are used.

Ver también

pathlib.PurePath.full_match() and pathlib.Path.glob() methods, which call this function to implement pattern matching and globbing.

Nuevo en la versión 3.13.

Examples

Consider a directory containing the following files: 1.gif, 2.txt, card.gif and a subdirectory sub which contains only the file 3.txt. glob() will produce the following results. Notice how any leading components of the path are preserved.

>>> 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/']

Si un directorio contiene ficheros que comienzan con . no coincidirá por defecto. Por ejemplo, considera un directorio que contiene card.gif y .card.gif:

>>> import glob
>>> glob.glob('*.gif')
['card.gif']
>>> glob.glob('.c*')
['.card.gif']

Ver también

The fnmatch module offers shell-style filename (not path) expansion.

Ver también

El módulo pathlib ofrece objetos ruta de alto nivel.