Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - finding TTF files

Can anyone improve on this? I'm fairly new to python and am trying to write portable code. I need to locate a font file to pass to ImageDraw.Draw.Text.

import matplotlib.font_manager as fontman

def findFontFile(searchFont):
    fList = fontman.findSystemFonts(fontpaths=None, fontext='ttf')
    targetFont = []
    for row in fList:
        try:
            if searchFont in row:
                targetFont.append(row)
        except TypeError:
            pass
    return targetFont[0]

On my system this gives me:

>>> findFontFile('DejaVuSans.ttf')
'/usr/share/fonts/truetype/ttf-dejavu/DejaVuSans.ttf'

Which is exactly what I need. Does this look like it will work on Mac / Windows systems as well as Linux (tested on Linux)? Could it be done more efficiently? In a more readable style? Will Mac / Windows have a different font file naming format? Suggestions welcome.

like image 646
Dorsey Avatar asked Aug 11 '26 10:08

Dorsey


1 Answers

I would do a little rewrite like (some changes are just a matter of style, more python like):

   def find_font_file(query):
       matches = list(filter(lambda path: query in os.path.basename(path), fontman.findSystemFonts()))
       return matches

The caller would then decide the element to use (after checking permissions etc).

As for the compatibility you can view here that the lib uses a set of common directories for the "main" operating systems to search for fonts (X window manager (linux), windows and os x). But you can always pass the directories where you want to search if you have more information on the different environments where the app is going to run.

like image 180
cristiano2lopes Avatar answered Aug 13 '26 01:08

cristiano2lopes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!