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?
CodePudding user response:
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
CodePudding user response:
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)