views:

57

answers:

2

Hello guys! This is my first question.

My python script opens and reads from a present text file using the following simple funct:

open("config.ini", "r")

As this is a relative path it is supposed to work because config.ini is placed in the same directory like the script is when it is launched, that should be the current working dir.

In fact this works perfectly on all of my 3 linux boxes, but I have one user who demands support because he gets an error while opening config.ini. The error raises because

os.path.exists("config.ini")

returns false even if the file is there!

Trying to fix this problem we found out that the only way to make it work is to place config.ini in his home directory despite the supposed working directory is another.

Also, if my script tries to create a file in the present working directory, the file is always created in his home dir instead, and so I think that for some reason his working dir is always home!

How can I troubleshoot this problem? Maybe I could introduce absolute paths, but I am afraid that os.getcwd() would return the homedir instead of the correct one.

Should I maybe suggest this user to fix his machine in some way?

Sorry for this long question but english is not my first language and I am a beginner in coding, so have some difficulties to explain.

Thank you very much in advance! =)

+4  A: 

Could it be that the user is executing your script from his home directory?

I.e. suppose the script is in:

/home/user/test/foo/foo.py

But the user calls it thus:

/home/user> python test/foo/foo.py

In this case, the "current directory" the script sees is /home/user.

What you can do is find out the directory the script itself resides in by calling this function:

import os

def script_dir():
    return os.path.dirname(os.path.realpath(__file__))

It will always return the directory in which the script lives, not the current directory which may be different. You can then store your configuration file there safely.

Eli Bendersky
You are right!!In fact I asked the user and found out he was calling the script like:/home/user> python test/foo/foo.pyWhich i should have guessed also, indeed!Your answer, together with unubtu's one, will be really useful to avoid such problems in the future!! =)Thank you very much!!cheers!
sblanzio
A: 

Along the same lines as Eli Bendersky's suggestion, you might want to try:

os.path.exists(os.path.join(sys.path[0],"config.ini"))

since sys.path[0] should always be the directory in which the script resides.

unutbu
Thank you very much!! =)
sblanzio