How can I use a file inside my app folder in Python? Platform independent of course... something similar to this:
#!/bin/sh
mypath=${0%/*}
LIBDIR=$mypath/modules
How can I use a file inside my app folder in Python? Platform independent of course... something similar to this:
#!/bin/sh
mypath=${0%/*}
LIBDIR=$mypath/modules
In Python 3.4+ you can use
pathlib
:How it works: the
__file__
attribute contains the pathname of the file from which the module was loaded. You use it to initialize aPath
object , make the path absolute using theresolve()
method and replace the final path component using thewith_name()
method.or
depending upon whether it's a module (2) or a single script (1), and whether you're invoking it from the same directory (1), or from a different one (2).
Edit
Looking at the "attempt" you have in your question, I'd guess that you'd want (1).
You can use
os.path
and its functions, which take care of OS-specific paths:On Windows, it should print out with backslashes.
__file__
contains the module's location. Use the functions inos.path
to extract the directory from it.