There is a difference, though you wouldn't be able to tell from a single script.
__file__
is the full filename of a loaded module or script, so getting the parent directory of it with os.path.dirname(__file__)
gets you the directory that script is in.
Note: on Linux (and similar OSes), such a filename can be a symbolic link to the actual file which may reside somewhere else. You can use os.path.realpath()
to resolve through any such links, if needed, although you can typically use the symlink equivalently. On Windows these are less common, but similarly, you can resolve symbolic links through realpath()
.
os.getcwd()
gets you the current working directory. If you start a script from the directory the script is in (which is common), the working directory will be the same as the result from the call from os.path.dirname(__file__)
.
But if you start the script from another directory (i.e. python d:\some\path\script.py
), or if you change the working directory during the script (e.g. with os.chdir()
), the current working directory has changed, but the directory part of the script filename has not.
So, it depends on what you need:
- Need the directory your script file is in? Use
os.path.dirname(__file__)
- Need the directory your script is currently running in? use
os.getcwd()
You'll see /
in some results and \
in others. Sadly, MS Windows uses \
to separate parts of a path (e.g. C:\Program Files\App\
), while pretty much all other operating systems use /
(e.g. /home/user/script.py
)
Python will often convert those automatically, so you can use paths like C:/Program Files/App
in Python on Windows as well, but it tends to be a good idea to be safe and use os.path.sep
.
Note: if you're on Python 3, you may be better off just using pathlib
's Path
instead of os.path
. It automatically resolves symbolic links (although you can still resolve to the link if you prefer) and has other nice conveniences as well.