howoto fix working directory is always home? (python)
Question: 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! =)


Answer: 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.

