Jeffery Tang
Jeffery Tang

Reputation: 393

Relative paths depend on where I run the python script

So I have this font ./files/resources/COMIC.TTF

And I reference the font like this: font = pygame.font.Font('./files/resources/COMIC.TTF', 12)

So I ran this on cmd python files/opencv_ball_tracker.py and sure enough it works.

But when I cd files then run python opencv_ball_tracker.py it fails with FileNotFoundError: [Errno 2] No such file or directory: './files/resources/COMIC.TTF'.

How do I make it so that it works no matter where I run the file?

Upvotes: 2

Views: 1276

Answers (2)

wombat
wombat

Reputation: 698

One way you could do this is to use pathlib. The syntax is a little unusual, but it does what you need. I'm assuming here that the file you are executing is run at the root.

from pathlib import Path
font_path = Path(__file__).parent / "files" / "resources" / "COMIC.TTF"
font_absolute_path = font_path.absolute()
print(font_absolute_path)

Upvotes: 1

JohnT
JohnT

Reputation: 50

you could use the absolute pathing, so if your using windows use "C:/XXX/XXX/files/resources/COMIC.TTF".

for linux/MAC it would be same but change the C:/ to the respective one for UNIX machines (I know for Mac it would be /Users/XXX/files/resources/COMIC.TTF)

Edit: If you wanted to use relative pathing I think you would need to copy the files folder with the python script and run it with the folder in there OR add it to your python pathing

Upvotes: 1

Related Questions