0

I want to open the font in folder 1 and folder 2. I wrote openOTF.py to open them.

Desktop 
├── openOTF.py
├── 1
│   ├── CMBSY7.otf
│   ├── CMBSY8.otf
│   └── CMBSY9.otf
├── 2
│   ├── CMCSC8.otf
│   └── CMCSC9.otf

this is openOTF.py

import fontforge as ff
import os

folders = ["1/", "2/"]

for folder in folders:
    os.chdir(folder)
    print(os.getcwd())
    files = os.listdir("./")
    for font in files:
        print(font)
        f = ff.open(font)
        print(f.path)
    os.chdir("../")

but this is the output of python open-otf.py, which cannot find CMCSC8.otf in folder 2, in fact it want to search /home/firestar/Desktop/1/CMCSC8.otf:

/home/firestar/Desktop/1
CMBSY9.otf
/home/firestar/Desktop/1/CMBSY9.otf
CMBSY8.otf
/home/firestar/Desktop/1/CMBSY8.otf
CMBSY7.otf
/home/firestar/Desktop/1/CMBSY7.otf
/home/firestar/Desktop/2
CMCSC8.otf
The requested file, CMCSC8.otf, does not exist
Traceback (most recent call last):
  File "/home/firestar/Desktop/open-otf.py", line 12, in <module>
    f = ff.open(font)
OSError: Open failed

it seems that os.chdir("../") changed the path to folder 2 but fontforge did not change the path (still in folder 1).

  • 1
    you should be iterating over the directories and files. There are a lot of posts and answers on how to do that. Then just pass the full path of the files that you want to retrieve to `open`. You don't need to change directories – 2293980990 May 26 '22 at 03:45
  • @2293980990 can I use relative paths when iterating? you know, something like `./*/*.otf` –  May 26 '22 at 03:46
  • Here's an [example](https://stackoverflow.com/questions/954504/how-to-get-files-in-a-directory-including-all-subdirectories) using `walk`. – 2293980990 May 26 '22 at 03:48
  • Alternatively use [`glob`](https://docs.python.org/3/library/glob.html), e.g. `glob.glob('*/*.otf')` from the same working directory as `openOTF.py`. – metatoaster May 26 '22 at 03:54
  • what is the equivalent command for `glob.glob('*/*.otf')` using `import os`? @metatoaster –  May 28 '22 at 06:45

1 Answers1

0
import fontforge as ff
import glob

files = glob.glob('*/*.otf')
print(files)

for font in files:
    f = ff.open(font)
    print(f.path)

I think glob is the simplest solution