Advertisement
Guest User

xglob.py

a guest
Sep 22nd, 2017
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.09 KB | None | 0 0
  1. # This extends the functionality of the built-in module `glob`.
  2. # Author: Sebastian Linke
  3. # Date: 22.09.2017
  4.  
  5. # This code may be used and distributed in accordance with the license terms
  6. # of GNU LGPL 3 (http://www.gnu.org/licenses/lgpl-3.0-standalone.html).
  7.  
  8. import glob
  9. import os
  10.  
  11. def get_filenames(path=os.curdir):
  12.     """
  13.    Return an iterator of the filenames in `path`. If this function could not
  14.    retrieve any filename due to access errors then the iterator will be empty
  15.    (i.e. yielding no items).
  16.  
  17.    Note that shell-like globbing is performed if `path` contains wildcard
  18.    symbols such as "*" or "?". The function will then return all names that
  19.    match the given pattern instead of their directory contents. If you need the
  20.    contents then you should put the platform's path separator at the end of
  21.    your pattern. In other words (on Windows):
  22.  
  23.    r'Python27'   => Content of "Python27"-folder (no wildcards -> no slash)
  24.    r'Py*'        => Names starting with "Py" (e.g. "Python27", "Python36", ...)
  25.    r'Py*\\'      => Contents of folders starting with "Py" (escaped "\")
  26.    r'Py*\*.txt'  => All text files in all Python folders
  27.  
  28.    To make life easier, you are free to use alternative path separators if
  29.    they are supported by your platform (e.g. "/" instead of "\" on Windows).
  30.  
  31.    Additionally, the "~"-symbol will be expanded to the user's home directory.
  32.    """
  33.     path = os.path.expanduser(os.path.expandvars(path))
  34.     if os.altsep is not None:
  35.         # "C:/Folder/file.txt" -> "C:\Folder\file.txt"
  36.         path = path.replace(os.altsep, os.sep)
  37.     if not glob.has_magic(path) or path.endswith(os.sep):
  38.         # "C:\Folder\" -> "C:\Folder\*"
  39.         # (this makes `glob` picking the contents)
  40.         path = os.path.join(path, '*')
  41.     filenames = (fn.rstrip(os.sep) for fn in glob.iglob(path))
  42.     if not glob.has_magic(os.path.dirname(path)):
  43.         # "C:\Folder\" -> ['a.txt', 'b.txt', ...]
  44.         # "C:\F*\" -> ['C:\Folder\a.txt', 'C:\Foo\b.txt', ...]
  45.         filenames = (os.path.basename(fn) for fn in filenames)
  46.     return filenames
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement