hi everyone. Say I have my project directorys set up like so:

/glider
/libs

/graphics
/rooms
room images go here

I'm trying to access a image from graphics/rooms, but from classes.py. I'm using pygame, and I know to go back a folder in a dir; you use:

#  go back a folder and load an image
pygame.image.load( '..\image.bmp' )

but how would I go from to graphics/rooms/room.bmp? I thought of using:

pygame.image.load( '..\graphics/rooms/room.bmp' )

you think you could use that, but it doesn't work... anyone know what could be the problem? any comments or help would be great. Thanks!

Dani AI

Generated

Short answer: relative file names are resolved against the process current working directory (os.getcwd()), not automatically relative to the module file that contains the code. In your layout (main.py in glider/, classes.py in libs/) the path a plain string points to depends on where you start Python. As suggested, build platform-safe paths instead of hand-writing separators; as discovered, a literal ..\graphics/... in classes.py can point to the wrong place when the program is started from somewhere else.

A reliable pattern is to construct an absolute path from the module file location (so the code in libs/classes.py computes the correct path regardless of CWD). Example using os.path:

import os

here = os.path.dirname(__file__)                # libs/
project_root = os.path.abspath(os.path.join(here, '..'))
img = os.path.join(project_root, 'graphics', 'rooms', 'room.bmp')

A cleaner modern alternative uses pathlib:

from pathlib import Path

img_path = (Path(__file__).resolve().parent.parent / 'graphics' / 'rooms' / 'room.bmp')
img = str(img_path)   # pass this string to pygame

Practical tips: first print or log os.getcwd() while running to see what CWD actually is. Avoid relying on changing CWD at runtime. Prefer centralizing resource loading (e.g., compute resource paths in main and pass them into classes) or package assets and load them with package-aware APIs (importlib.resources / package_data) so your code works when installed or frozen. Also avoid manual backslashes in strings—use os.path/pathlib to stay cross-platform.

Recommended Answers

All 2 Replies

Have a look at:
http://docs.python.org/library/os.path.html

You probably need some of the following:
os.getcwd()
os.path.join()
os.path.listdir()
os.path.isdir()
os.path.isfile()

Try to use these functions and not the literal path. This way, your program will be cross-platform and you will avoid such errors about / and \

thanks, but I forgot to mention something. There is a file called that is in the glider folder. calls classes.py. So is my program trying to access the image files from or ?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.