Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # This extends the functionality of the built-in module `glob`.
- # Author: Sebastian Linke
- # Date: 22.09.2017
- # This code may be used and distributed in accordance with the license terms
- # of GNU LGPL 3 (http://www.gnu.org/licenses/lgpl-3.0-standalone.html).
- import glob
- import os
- def get_filenames(path=os.curdir):
- """
- Return an iterator of the filenames in `path`. If this function could not
- retrieve any filename due to access errors then the iterator will be empty
- (i.e. yielding no items).
- Note that shell-like globbing is performed if `path` contains wildcard
- symbols such as "*" or "?". The function will then return all names that
- match the given pattern instead of their directory contents. If you need the
- contents then you should put the platform's path separator at the end of
- your pattern. In other words (on Windows):
- r'Python27' => Content of "Python27"-folder (no wildcards -> no slash)
- r'Py*' => Names starting with "Py" (e.g. "Python27", "Python36", ...)
- r'Py*\\' => Contents of folders starting with "Py" (escaped "\")
- r'Py*\*.txt' => All text files in all Python folders
- To make life easier, you are free to use alternative path separators if
- they are supported by your platform (e.g. "/" instead of "\" on Windows).
- Additionally, the "~"-symbol will be expanded to the user's home directory.
- """
- path = os.path.expanduser(os.path.expandvars(path))
- if os.altsep is not None:
- # "C:/Folder/file.txt" -> "C:\Folder\file.txt"
- path = path.replace(os.altsep, os.sep)
- if not glob.has_magic(path) or path.endswith(os.sep):
- # "C:\Folder\" -> "C:\Folder\*"
- # (this makes `glob` picking the contents)
- path = os.path.join(path, '*')
- filenames = (fn.rstrip(os.sep) for fn in glob.iglob(path))
- if not glob.has_magic(os.path.dirname(path)):
- # "C:\Folder\" -> ['a.txt', 'b.txt', ...]
- # "C:\F*\" -> ['C:\Folder\a.txt', 'C:\Foo\b.txt', ...]
- filenames = (os.path.basename(fn) for fn in filenames)
- return filenames
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement