Skip to content

Instantly share code, notes, and snippets.

@pklaus
Created January 4, 2016 12:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pklaus/6a85725e0e9ca7d2aeb3 to your computer and use it in GitHub Desktop.
Save pklaus/6a85725e0e9ca7d2aeb3 to your computer and use it in GitHub Desktop.
List the names of OpenType (.otf) fonts in a directory (and optionally rename them accordingly).
#!/usr/bin/env python
""" Taken from http://stackoverflow.com/a/23703564/183995 """
import os, sys, argparse
from bitstring import BitStream
parser = argparse.ArgumentParser()
parser.add_argument('folder')
parser.add_argument('--rename', action='store_true')
args = parser.parse_args()
font_path = args.folder
font_count = 0
for file in os.listdir(font_path):
if file.lower().endswith(".otf"):
source_file_name = os.path.join(font_path, file)
font = BitStream(filename=source_file_name)
pos = font.find('0x00010101', bytealigned=True)
if not pos:
sys.stderr.write("Couldn't read the font file %s" % (source_file_name))
continue # this skips bad otf files ;-)
font.pos = pos[0]-16
fontstring = font.read(8).hex
new = pos[0]+4 #afaik bitstring has no regex/wildcards support...
while fontstring != "04": #so we do this similar... 04 ?? 00 01 01 01 [String] 00 01
pos = font.find('0x00010101',new, bytealigned=True)
font.pos = pos[0]-16
fontstring = font.read(8).hex
new = pos[0]+4
font_count += 1
pos2 = font.find('0x0001',pos[0]+5, bytealigned=True)
length = pos2[0]-pos[0]-40
font.pos = pos[0]+40
fontstring = font.read(length)
hex_data = fontstring.hex
ascii_string = ""
x = 0
y = 2
l = len(hex_data)
while y <= l:
ascii_string += chr(int(hex_data[x:y], 16))
x += 2
y += 2
print (ascii_string)
#the next three lines if you want autorename
if args.rename:
newfile = os.path.join(font_path, ascii_string+".otf")
if not os.path.isfile(newfile):
os.rename(source_file_name, newfile)
print()
print(font_count, "Fonts")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment