Skip to content

Commit d52cb19

Browse files
feat: file_matching_regex - Find matching files using re and fnmatch
1 parent 77aa5b7 commit d52cb19

File tree

6 files changed

+19
-0
lines changed

6 files changed

+19
-0
lines changed

ebook/chapters/standard_lib_chapters/files.tex

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,3 +22,12 @@ \subsection{Read Files using Iterator}
2222
If using iterators, only the next line is loaded.
2323

2424
\lstinputlisting[caption=read\_files\_using\_iterator.py]{../standard_lib/read_files_using_iterator.py}
25+
26+
27+
\subsection{File Matching Using \lstinline{fnmatch}}
28+
29+
Matching certain strings is easy if you use Pythons built-in \lstinline{fnmatch} module.
30+
It even provides you functionality to translate the easy to use \lstinline{fnmatch} patterns into regular expressions.
31+
The following recipe shows you a sample usage filtering markdown files and \lstinline{git}-related files in your current working directory.
32+
33+
\lstinputlisting[caption=file\_matching\_regex.py]{../standard_lib/file_matching_regex.py}

ebook/python-snippets.epub

420 Bytes
Binary file not shown.

ebook/python-snippets.mobi

664 Bytes
Binary file not shown.

ebook/python-snippets.pdf

1.65 KB
Binary file not shown.

standard_lib/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ A collection of useful snippets using only the standard library.
2222
| disassemble_bytecode | Shows the bytecode representation of f-strings and str() conversion of integers |
2323
| drawing_turtle | Drawing a dragon symbol using Python's built-in turtle |
2424
| emulate_switch_case | Emulate switch-case-statements as they don't exist in Python |
25+
| file_matching_regex | Find matching files using `re` and `fnmatch` |
2526
| fill_zeros | Fill strings using leading zeros. |
2627
| flatten | Flatten a nested iterable |
2728
| function_arguments | Example on how to (not) use function arguments |

standard_lib/file_matching_regex.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
import fnmatch
2+
import os
3+
import re
4+
5+
6+
reg = "({})|({})".format(fnmatch.translate("*.md"), fnmatch.translate("*.git*"))
7+
markdown_files = [f for f in os.listdir() if re.match(reg, f)]
8+
9+
print(markdown_files)

0 commit comments

Comments
 (0)