Glob python несколько расширений

glob — Unix style pathname pattern expansion¶

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.scandir() and fnmatch.fnmatch() functions in concert, and not by actually invoking a subshell.

Note that files beginning with a dot ( . ) can only be matched by patterns that also start with a dot, unlike fnmatch.fnmatch() or pathlib.Path.glob() . (For tilde and shell variable expansion, use os.path.expanduser() and os.path.expandvars() .)

For a literal match, wrap the meta-characters in brackets. For example, ‘[?]’ matches the character ‘?’ .

The pathlib module offers high-level path objects.

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 be included is unspecified.

If root_dir is not None , it should be a path-like object specifying the root directory for searching. It has the same effect on glob() as changing the current directory before calling it. If pathname is relative, the result will contain paths relative to root_dir.

This function can support paths relative to directory descriptors with the dir_fd parameter.

Читайте также:  METANIT.COM

If recursive is true, the pattern “ ** ” will match any files and zero or more directories, subdirectories and symbolic links to directories. If the pattern is followed by an os.sep or os.altsep then files will not match.

If include_hidden is true, “ ** ” pattern will match hidden directories.

Raises an auditing event glob.glob with arguments pathname , recursive .

Raises an auditing event glob.glob/2 with arguments pathname , recursive , root_dir , dir_fd .

Using the “ ** ” pattern in large directory trees may consume an inordinate amount of time.

Changed in version 3.5: Support for recursive globs using “ ** ”.

Changed in version 3.10: Added the root_dir and dir_fd parameters.

Changed in version 3.11: Added the include_hidden parameter.

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

Return an iterator which yields the same values as glob() without actually storing them all simultaneously.

Raises an auditing event glob.glob with arguments pathname , recursive .

Raises an auditing event glob.glob/2 with arguments pathname , recursive , root_dir , dir_fd .

Changed in version 3.5: Support for recursive globs using “ ** ”.

Changed in version 3.10: Added the root_dir and dir_fd parameters.

Changed in version 3.11: Added the include_hidden parameter.

Escape all special characters ( ‘?’ , ‘*’ and ‘[‘ ). This is useful if you want to match an arbitrary literal string that may have special characters in it. Special characters in drive/UNC sharepoints are not escaped, e.g. on Windows escape(‘//?/c:/Quo vadis?.txt’) returns ‘//?/c:/Quo vadis[?].txt’ .

For example, 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('./6.*') ['./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/'] 

If the directory contains files starting with . they won’t be matched by default. For example, consider a directory containing card.gif and .card.gif :

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

Shell-style filename (not path) expansion

Источник

Python Glob несколько типов файлов

Есть ли лучший способ использовать glob.glob в python, чтобы получить список из нескольких типов файлов, таких как .txt,.mdown и .markdown? Прямо сейчас у меня есть что-то вроде этого:

projectFiles1 = glob.glob( os.path.join(projectDir, '*.txt') ) projectFiles2 = glob.glob( os.path.join(projectDir, '*.mdown') ) projectFiles3 = glob.glob( os.path.join(projectDir, '*.markdown') ) 

27 ответов

Может быть, есть лучший способ, но как насчет:

>>> import glob >>> types = ('*.pdf', '*.cpp') # the tuple of file types >>> files_grabbed = [] >>> for files in types: . files_grabbed.extend(glob.glob(files)) . >>> files_grabbed # the list of pdf and cpp files 

Возможно, есть и другой способ, поэтому подождите, если кто-то другой найдет лучший ответ.

Это дважды зацикливает список файлов. В первой итерации проверяется * .pdf, а во второй проверяется * .cpp. Есть ли способ сделать это за одну итерацию? Проверять комбинированное состояние каждый раз?

from glob import glob files = glob('*.gif') files.extend(glob('*.png')) files.extend(glob('*.jpg')) print(files) 

Если вам нужно указать путь, перебрать шаблоны соответствия и сохранить соединение внутри цикла для простоты:

from os.path import join from glob import glob files = [] for ext in ('*.gif', '*.png', '*.jpg'): files.extend(glob(join("path/to/dir", ext))) print(files) 
import itertools as it, glob def multiple_file_types(*patterns): return it.chain.from_iterable(glob.iglob(pattern) for pattern in patterns) 
for filename in multiple_file_types("*.txt", "*.sql", "*.log"): # do stuff 

Я нашел то же решение, но не знал о chain.from_iterable . Так что это похоже, но менее читабельно: it.chain(*(glob.iglob(pattern) for pattern in patterns)) .

glob возвращает список: почему бы просто не запускать его несколько раз и не конкатенировать результаты?

from glob import glob ProjectFiles = glob('*.txt') + glob('*.mdown') + glob('*markdown') 

Это, пожалуй, самое читаемое решение. Я бы изменил случай с ProjectFiles на projectFiles , но отличное решение.

с glob это невозможно. вы можете использовать только:
* соответствует всем
? соответствует любому одиночному символу
[seq] соответствует любому символу в seq
[! seq] соответствует любому символу не в секундах

используйте os.listdir и regexp для проверки шаблонов:

for x in os.listdir('.'): if re.match('.*\.txt|.*\.sql', x): print x 

Мне нравится такой подход — если выразительность glob недостаточно мощна, перейдите на более мощную систему регулярных выражений, не взламывайте ее, например, с помощью itertools потому что последующие изменения шаблона также должны быть хакерскими (скажем, вы хотите разрешить прописные и строчные буквы) ). Да, и было бы чище написать ‘.*\.(txt|sql)’

Например, для *.mp3 и *.flac для нескольких папок вы можете:

mask = r'music/*/*.[mf][pl][3a]*' glob.glob(mask) 

Идея может быть расширена до большего количества расширений файлов, , но вам нужно проверить, не будут ли сочетания не соответствовать никакому другому нежелательному расширению файла, которое может быть у вас в этих папках. Поэтому будьте осторожны с этим.

Один лайнер, Только для черта.

folder = "C:\\multi_pattern_glob_one_liner" files = [item for sublist in [glob.glob(folder + ext) for ext in ["/*.txt", "/*.bat"]] for item in sublist] 
['C:\\multi_pattern_glob_one_liner\\dummy_txt.txt', 'C:\\multi_pattern_glob_one_liner\\dummy_bat.bat'] 

Придя сюда за помощью, я сделал свое собственное решение и хотел поделиться им. Он основан на ответе user2363986, но я думаю, что это более масштабируемо. Это означает, что если у вас 1000 расширений, код будет выглядеть несколько элегантно.

from glob import glob directoryPath = "C:\\temp\\*." fileExtensions = [ "jpg", "jpeg", "png", "bmp", "gif" ] listOfFiles = [] for extension in fileExtensions: listOfFiles.extend( glob( directoryPath + extension )) for file in listOfFiles: print(file) # Or do other stuff 

Мне нужно больше информации, чтобы отладить это для вас . Вы получаете исключение? Кроме того, если вы работаете в Windows, этот путь не выглядит так, как будто он будет работать (отсутствует буква диска).

Ниже приведен однострочный вариант ответа на вопрос Пата (который также включает в себя то, что вы хотели поместить в определенную директорию проекта):

import os, glob exts = ['*.txt', '*.mdown', '*.markdown'] files = [f for ext in exts for f in glob.glob(os.path.join(project_dir, ext))] 

Вы перебираете расширения ( for ext in exts ), а затем для каждого расширения берете каждый файл, соответствующий шаблону glob ( for f in glob.glob(os.path.join(project_dir, ext) ).

Это короткое решение без лишних циклов for, вложенных списков и функций, которые не загромождают код. Просто чистый, выразительный, питонический дзен.

Это решение позволяет вам иметь собственный список exts который может быть изменен без обновления вашего кода. (Это всегда хорошая практика!)

Понимание списка такое же, как и в решении Лорана (за которое я голосовал). Но я бы сказал, что обычно нет необходимости выделять одну строку в отдельную функцию, поэтому я предоставляю это в качестве альтернативного решения.

Если вам нужно выполнить поиск не только в одном каталоге, но и во всех подкаталогах, вы можете передать recursive=True и использовать глобальный символ мультикаталога ** 1 :

files = [f for ext in exts for f in glob.glob(os.path.join(project_dir, '**', ext), recursive=True)] 

Это вызовет glob.glob(‘/**/*.txt’, recursive=True) и так далее для каждого расширения.

1 Технически символ » ** просто соответствует одному или нескольким символам, включая косую черту / (в отличие от единственного символа » * ). На практике вам просто нужно помнить, что, пока вы окружаете ** косыми чертами (разделителями пути), оно соответствует нулю или большему количеству каталогов.

Источник

Оцените статью