简体   繁体   中英

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?

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM