Starting from Python 3.5 there is a new package in the standard Python library called pathlib
. In it, the class Path
allows various types of operation with directories or files, including shortcuts for reading and writing direct files. In fact, all methods and ways to handle files that are scattered in previous versions of Python in the modules os
, os.path
, glob
, shutils
beyond the very open
can be centered on the dots or attributes of pathlib.Path
. Be sure to see the documentation on https://docs.python.org/3/library/pathlib.html
Among the methods of pathlib.Path
, there’s the glob
, which is more powerful than the glob of glob.glob
- since it not only matches filenames, but also returns objects Path
, ready to be used in any situation - and of which can be seen either the complete path, or the name, or any part of the path to the file.
This method also allows, as the glob.glob
the use of two "**" to search in all corresponding subdirectories -
import pathlib
lista = list(pathlib.Path(".").glob("**/*py"))
Within the list variable, you will have a "Path" object for each file . py from the current directory (indicated by the initial directory "." in the expression).
If you only need the folders containing the files. py, and not the files themselves, the attribute "Parent" of each "Path" object is a "Path" to the folder where the file is - one can use a comprehension to get the "Parent" of all files obtained with the above expression and put them in a set (object of type set
), that elinina duplicates. As in addition you will turn into Json, and do not open the folders themselves, it is important to transform that set containing Path
s in a simple list containing strings ( str
), since the serialization for Json does not accept nor set
s, nor Path
s.
It seems complicated, but the code is just this:
lista = list(set(str(path.parent) for path in pathlib.Path(".").glob("**/*py")))
(that is, for each Path located with the glob, extract the . Parent, and transform into str, and that str will be an item of a set - at the end of the operation, transform the set
back on a list (list
).
Python also accepts creating sets automatically in comprehensions, using { }
instead of the call to set
:
lista = list({str(path.parent) for path in pathlib.Path(".").glob("**/*py")})
hi - thank you! you understand ideally that the "answer accepted" check is to mark the answer that best met your needs, or that you judge more correct, is not it? and we reserve the answers for texts realment answering the question.
– jsbueno