Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

help with os.getcwd() in a menu

Status
Not open for further replies.

forrestcupp

Programmer
Jul 22, 2006
25
I am using Python in Ubuntu Linux with pygtk. In my program I use os.getcwd() to get the current working directory to load image files to show in my window. I have no problems when I either run the program from the command line, or if I run it from nautilus. But I made a link to the program in my gnome/applications menu, and when I run from the menu, os.getcwd() doesn't return the directory that the program is in, so it can't find the images. Temporarily I've just made a string variable dir='/home/CORRECT DIRECTORY' and am using that, but that isn't sufficient if I move the program to another directory, or put it on a different computer. Is there a way to make this work.
 
You may use
Code:
os.path.dirname(__file__)
trick

[small]Dmitry V Selitsky[/small]​
 
You may use
CODE
os.path.dirname(__file__)
trick


Could you please explain more about how to use this? I tried it, and it didn't work. I read about it in the Python reference library, and that didn't help me much. From what I read about it, it doesn't seem like that is what I'm looking for. If you know how to use this in a way that would help me, can you show me, please?
 
forrestcupp said:
Could you please explain more about how to use this? I tried it, and it didn't work. I read about it in the Python reference library, and that didn't help me much. From what I read about it, it doesn't seem like that is what I'm looking for. If you know how to use this in a way that would help me, can you show me, please?

Imagine, that your program organized in such dirs:
[tt]
/
home/
my_py_project/
images/
util/
main.py
[/tt]

To define from main.py the relative path to [images] directory, use
Code:
import os
staticDirPath = os.path.dirname(__file__) + os.sep + 'images'

[small]Dmitry V Selitsky, t o r m o z @ g m x . n e t[/small]​
 
Thank you very much. my problem was that instead of entering (__file__) I thought I was supposed to put the actual file name there. This worked perfectly. I assume that os.sep will put a / for unix and a \ for windows. Is that right?
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top