Retrieve filetype:pdf from library I retrieved all the books in pdf from my library with a recursive function.

import os

def walk(dirname):
    for name in os.listdir(dirname):
        path = os.path.join(dirname, name)

        if os.path.isfile(path) and path.endswith('pdf'):
            books.append(path)
        if os.path.isdir(path):
            walk(path)
def main():
    dir = '~/Documents/MyLibrary/'
    global books
    books = []
    walk(dir)
    print(books)

if __name__ == "__main__":
    main()
Similarly to a feature in most UNIX shells, Python has a globbing module, called glob.

It even supports the extended globbing (using ** to recursively descend into sub-folders) since Python 3.5, which you can use like this:

import os
from glob import glob

if __name__ == "__main__":
    dir = os.path.expanduser('~/Documents/MyLibrary/')
    books = glob(os.path.join(dir, "**/*.pdf"), recursive=True)
    print(books)


Here I also used the os.path module to correctly join the paths and expand the ~ symbol to the users home directory.



Alternatively, you could use the pathlib.Path object (introduced in Python 3.4), which also supports globbing:

from pathlib import Path

if __name__ == "__main__":
    dir = Path('~/Documents/MyLibrary/').expanduser()
    books = list(dir.glob('**/*.pdf'))
    print(books)


Note the list call, which is necessary, because the Path.glob method returns a generator (in contrast to glob.glob, which returns a list).