|
| 1 | +.. _globbing: |
| 2 | + |
| 3 | +Globbing |
| 4 | +======== |
| 5 | + |
| 6 | +Globbing is the process of matching paths according to the rules used |
| 7 | +by the Unix shell. |
| 8 | + |
| 9 | +Generally speaking, you can think of a glob pattern as a path containing |
| 10 | +one or more wildcard patterns, separated by forward slashes. |
| 11 | + |
| 12 | + |
| 13 | +Matching Files and Directories |
| 14 | +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 15 | + |
| 16 | +In a glob pattern, A ``*`` means match anything text in a filename. A ``?`` |
| 17 | +matches any single character. A ``**`` matches any number of subdirectories, |
| 18 | +making the glob *recusrive*. If the glob pattern ends in a ``/``, it will |
| 19 | +only match directory paths, otherwise it will match files and directories. |
| 20 | + |
| 21 | +.. note:: |
| 22 | + A recursive glob requires that PyFilesystem scan a lot of files, |
| 23 | + and can potentially be slow for large (or network based) filesystems. |
| 24 | + |
| 25 | +Here's a summary of glob patterns: |
| 26 | + |
| 27 | +``*`` |
| 28 | + Matches all files in the current directory. |
| 29 | +``*.py`` |
| 30 | + Matches all .py file in the current directory. |
| 31 | +``*.py?`` |
| 32 | + Matches all .py files and .pyi, .pyc etc in the currenct directory. |
| 33 | +``project/*.py`` |
| 34 | + Matches all .py files in a directory called ``project``. |
| 35 | +``*/*.py`` |
| 36 | + Matches all .py files in any sub directory. |
| 37 | +``**/*.py`` |
| 38 | + Recursively matches all .py files. |
| 39 | +``**/.git/`` |
| 40 | + Recursively matches all the git directories. |
| 41 | + |
| 42 | + |
| 43 | +Interface |
| 44 | +~~~~~~~~~ |
| 45 | + |
| 46 | +PyFilesystem supports globbing via the ``glob`` attribute on every FS |
| 47 | +instance, which is an instance of :class:`~fs.glob.BoundGlobber`. Here's |
| 48 | +how you might use it to find all the Python files in your filesystem:: |
| 49 | + |
| 50 | + for match in my_fs.glob("**/*.py"): |
| 51 | + print(f"{match.path} is {match.info.size} bytes long") |
| 52 | + |
| 53 | +Calling ``.glob`` with a pattern will return an iterator of |
| 54 | +:class:`~fs.glob.GlobMatch` named tuples for each matching file or |
| 55 | +directory. A glob match contains two attributes; ``path`` which is the |
| 56 | +full path in the filesystem, and ``info`` which is an |
| 57 | +:class:`fs.info.Info` info object for the matched resource. |
| 58 | + |
| 59 | + |
| 60 | +Batch Methods |
| 61 | +~~~~~~~~~~~~~ |
| 62 | + |
| 63 | +In addition to iterating over the results, you can also call methods on |
| 64 | +the :class:`~fs.glob.Globber` which apply to every matched path. |
| 65 | + |
| 66 | +For instance, here is how you can use glob to remove all ``.pyc`` files |
| 67 | +from a project directory:: |
| 68 | + |
| 69 | + >>> import fs |
| 70 | + >>> fs.open_fs('~/projects/my_project').glob('**/*.pyc').remove() |
| 71 | + 29 |
| 72 | + |
0 commit comments