python os.path.join(os.getcwd(), 'folder', 'file') returns different paths in same file

Viewed 870

I am trying to add a specific font to my fpdf configuration using .add_font(). I used to have all my scripts in a folder called "david" since I rewrote the Code I am working on. Now I migrated it into the parent directory.

Here is the unexpected behaviour: In a function I call

# returns /home/path_to_dir/fonts/DejaVuSans.ttf (as expected)
print(os.path.join(os.getcwd(), "fonts", "DejaVuSans.ttf"))
pdf.add_font(
    "DejaVu",
    "",
    # returns /home/path_to_dir/david/../fonts/DejaVuSans.ttf (old path)
    os.path.join(os.getcwd(), "fonts", "DejaVuSans.ttf"),
    uni=True,
)

I deleted all pycache files and if I add an empty directory called "david" everything works again since the latter path can be resolved.

reproducable minimal example: - To get fpdf working: - pip install fpdf - a fonts directory with a font in it (ttf format)

A file with this code in it

import fpdf
import os


def reproducable_example():
    text = ['This is some test text', 'This is some more test text']
    pdf = fpdf.FPDF()
    print(os.path.join(os.getcwd(), '../fonts', 'DejaVuSans.ttf'))
    pdf.add_font(
        "DejaVu",
        "",
        os.path.join(os.getcwd(), "../fonts", "DejaVuSans.ttf"),
        uni=True,
    )
    pdf.set_font('DejaVu', "", 12)
    pdf.add_page()
    for string in text:
        pdf.multi_cell(0, 10, txt=string)
    pdf.output(os.path.join(os.getcwd(), 'text.pdf'))


reproducable_example()

It would obviously be very strange if the second call to os.getcwd() would include a folder with the name 'david'. Therefore you probably have to put the code in a nested folder with the name 'david' first then run it, and then put it into the parent folder, delete the 'david' directory and run it again.

Also I created a .workspace folder in which i have my launch.json file. In this file I changed the cwd key from ${workspaceRoot} to ${workspaceRoot}/david because of Import issues when using the vscode debugger. I changed this back when I migrated the files to the parent directory.

This is why you can run os.getcwd() in the child folder and then step out of manually

Nowhere in my whole workspace did I declare the wrong filepath but it still gets used by the .add_font() method even when I hardcode the correct path into it

Solution: When I ran the script, a .pkl file was created automatically. You need to delete this file when you change the directory of your script or it will use the stored paths

0 Answers
Related