Python filter file names

fnmatch — Соответствие шаблону имени файла Unix¶

Данный модуль обеспечивает поддержку подстановочных знаков в стиле оболочки Unix, которые не являются регулярными выражениями (задокументированы в модуле re ). В подстановочных знаках в стиле оболочки используются специальные символы:

Шаблон Значение
* соответствует всему
? соответствует любому единичному символу
[seq] соответствует любому символу в seq
[!seq] соответствует любому символу не в seq

Для буквального соответствия заключите метасимволы в скобки. Например, ‘[?]’ соответствует символу ‘?’ .

Обратите внимание, что разделитель имён файлов ( ‘/’ в Unix) не является специальным для данного модуля. См. модуль glob для расширения пути ( glob использует filter() для соответствия сегментам пути). Точно так же имена файлов, начинающиеся с точки, не являются специальными для этого модуля и соответствуют шаблонам * и ? .

fnmatch. fnmatch ( filename, pattern ) ¶

Проверяет, соответствует ли строка filename строке pattern, возвращая True или False . Оба параметра нормализованы по регистру с использованием os.path.normcase() . fnmatchcase() можно использовать для сравнения с учётом регистра, независимо от того, является ли это стандартом для операционной системы.

В этом примере будут напечатаны все имена файлов в текущем каталоге с расширением .txt :

import fnmatch import os for file in os.listdir('.'): if fnmatch.fnmatch(file, '*.txt'): print(file) 

Проверяет, соответствует ли filename pattern, возвращая True или False ; сравнение чувствительно к регистру и не применяется os.path.normcase() .

Читайте также:  Php and or keywords

fnmatch. filter ( names, pattern ) ¶

Создаёт список из тех элементов итерируемого names, которые соответствуют pattern. Он такой же, как [n for n in names if fnmatch(n, pattern)] , но реализован более эффективно.

fnmatch. translate ( pattern ) ¶

Возвращает pattern в стиле оболочки, преобразованный в регулярное выражение для использования с re.match() .

>>> import fnmatch, re >>> >>> regex = fnmatch.translate(‘*.txt’) >>> regex ‘(?s:.*\\.txt)\\Z’ >>> reobj = re.compile(regex) >>> reobj.match(‘foobar.txt’)

Модуль glob Расширение пути в стиле оболочки Unix.

Источник

fnmatch — Unix filename pattern matching¶

This module provides support for Unix shell-style wildcards, which are not the same as regular expressions (which are documented in the re module). The special characters used in shell-style wildcards are:

matches any single character

matches any character in seq

matches any character not in seq

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

Note that the filename separator ( ‘/’ on Unix) is not special to this module. See module glob for pathname expansion ( glob uses filter() to match pathname segments). Similarly, filenames starting with a period are not special for this module, and are matched by the * and ? patterns.

Also note that functools.lru_cache() with the maxsize of 32768 is used to cache the compiled regex patterns in the following functions: fnmatch() , fnmatchcase() , filter() .

fnmatch. fnmatch ( filename , pattern ) ¶

Test whether the filename string matches the pattern string, returning True or False . Both parameters are case-normalized using os.path.normcase() . fnmatchcase() can be used to perform a case-sensitive comparison, regardless of whether that’s standard for the operating system.

This example will print all file names in the current directory with the extension .txt :

import fnmatch import os for file in os.listdir('.'): if fnmatch.fnmatch(file, '*.txt'): print(file) 

Test whether filename matches pattern, returning True or False ; the comparison is case-sensitive and does not apply os.path.normcase() .

fnmatch. filter ( names , pattern ) ¶

Construct a list from those elements of the iterable names that match pattern. It is the same as [n for n in names if fnmatch(n, pattern)] , but implemented more efficiently.

fnmatch. translate ( pattern ) ¶

Return the shell-style pattern converted to a regular expression for using with re.match() .

>>> import fnmatch, re >>> >>> regex = fnmatch.translate(‘*.txt’) >>> regex ‘(?s:.*\\.txt)\\Z’ >>> reobj = re.compile(regex) >>> reobj.match(‘foobar.txt’)

Unix shell-style path expansion.

Источник

11.8. fnmatch — Unix filename pattern matching¶

This module provides support for Unix shell-style wildcards, which are not the same as regular expressions (which are documented in the re module). The special characters used in shell-style wildcards are:

Pattern Meaning
* matches everything
? matches any single character
[seq] matches any character in seq
[!seq] matches any character not in seq

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

Note that the filename separator ( ‘/’ on Unix) is not special to this module. See module glob for pathname expansion ( glob uses fnmatch() to match pathname segments). Similarly, filenames starting with a period are not special for this module, and are matched by the * and ? patterns.

fnmatch. fnmatch ( filename, pattern ) ¶

Test whether the filename string matches the pattern string, returning True or False . Both parameters are case-normalized using os.path.normcase() . fnmatchcase() can be used to perform a case-sensitive comparison, regardless of whether that’s standard for the operating system.

This example will print all file names in the current directory with the extension .txt :

import fnmatch import os for file in os.listdir('.'): if fnmatch.fnmatch(file, '*.txt'): print(file) 

Test whether filename matches pattern, returning True or False ; the comparison is case-sensitive and does not apply os.path.normcase() .

fnmatch. filter ( names, pattern ) ¶

Return the subset of the list of names that match pattern. It is the same as [n for n in names if fnmatch(n, pattern)] , but implemented more efficiently.

fnmatch. translate ( pattern ) ¶

Return the shell-style pattern converted to a regular expression for using with re.match() .

>>> import fnmatch, re >>> >>> regex = fnmatch.translate(‘*.txt’) >>> regex ‘(?s:.*\\.txt)\\Z’ >>> reobj = re.compile(regex) >>> reobj.match(‘foobar.txt’)

Module glob Unix shell-style path expansion.

Источник

How To Use Python Fnmatch Module To Handle File Name Matching

Python fnmatch module can support UNIX shell style filename matching. And the python fnmatch matches support the following wildcards and functions.

1. Python fnmatch Module Supported Wildcards & Functions.

  1. *: it can match any character.
  2. ?: it can match any single character.
  3. >[character sequence]: it can match any character in the character sequence in brackets. The character sequence also supports middle line representation. For example, [a-c] can represent any of the characters in a, b, and c.
  4. >[! character sequence]: it can match any character not in the bracket character sequence.
  5. fnmatch.fnmatch(filename, pattern) , this function determines whether the specified file name matches the specified pattern.
  6. fnmatch.fnmatchcase(file name, pattern) : this function is similar to the previous function except that it is case sensitive.
  7. fnmatch.filter(names, pattern) : this function filters the names list and returns a subset of file names that match the patterns.
  8. fnmatch.translate(pattern) : this function is used to convert a UNIX shell style pattern to a regular expression pattern.

2. Python fnmatch Module Examples.

The following python code example demonstrates the above function usage.

fnmatch.fnmatch(filename, pattern): This example will filter out all the python files under the current directory.

from pathlib import * import fnmatch import os.path # Traverse all the files and subdirectories under the current directory curr_dir = Path('.') for f in curr_dir.iterdir(): # If the file name end with .py. if fnmatch.fnmatch(f, '*.py'): # Get the file absolute path. f_path = os.path.abspath('.') + '/'+f.name # Print the file path. print(f_path) ======================================================== Output /Users/Documents/WorkSpace/dev2qa.com-example-code/PythonExampleProject/com/dev2qa/example/file/FileOperateExample.py /Users/Documents/WorkSpace/dev2qa.com-example-code/PythonExampleProject/com/dev2qa/example/file/CheckFileExistExample.py /Users/Documents/WorkSpace/dev2qa.com-example-code/PythonExampleProject/com/dev2qa/example/file/OsWalk.py

fnmatch.filter(names, pattern)

import fnmatch if __name__ == '__main__': # Define a list contains 4 python file, fnmatch module do not care whether the files exists or not. file_names = ['a.py','b.py','c.py','d.py'] # Define a pattern string. name_pattern = '[bc].py' # Filter the python file name list with the file name pattern. sub_file_names = fnmatch.filter(file_names, name_pattern) # Print out the filter result. print(sub_file_names) ====================================================== Output ['b.py', 'c.py']

fnmatch.translate(pattern)

import fnmatch unix_pattern_str = '?.py' reg_pattern_str = fnmatch.translate(unix_pattern_str) print(reg_pattern_str) unix_pattern_str = '[a-z].py' reg_pattern_str = fnmatch.translate(unix_pattern_str) print(reg_pattern_str) unix_pattern_str = '[xyz].py' reg_pattern_str = fnmatch.translate(unix_pattern_str) print(reg_pattern_str) ======================================================= Output (?s:.\.py)\Z (?s:[a-z]\.py)\Z (?s:[xyz]\.py)\Z

Leave a Comment Cancel Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Источник

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