This is good advice for data files that are associated with a script or module. It’s not enough, however, without also discussing the use of
__file__. Normally, a module has a global variable named
__file__ that contains the path of the executed file. It isn’t always a full path, so first resolve the full path via
os.path.abspath(). Then get the path of the containing folder via
os.path.dirname(). For example:
_dir = os.path.dirname(os.path.abspath(__file__))
os.path.join() to get the full path of a file in this directory. For example:
filename = os.path.join(_dir, "regex_sum_1432265.txt")
If a script has to open many files relative to the script directory, it may be more convenient to make this the current working directory. For example:
I sometimes come across advice or casual use in online discussions that confuses the script directory with the current working directory. The two are generally unrelated. One connection between them is that if there’s no main script (e.g. for the REPL shell or a
-c command), by default the current working directory is added to
sys.path (for use by
import statements) as if it’s the ‘script directory’.
izan, the screenshot in your message does not show where Python is stored. It’s a folder of shell links (i.e. “.LNK” files) in the start menu. In particular, it’s a folder in “Microsoft\Windows\Start Menu\Programs”, which is relative to either the current user’s “%AppData%” folder or the system’s “%ProgramData%” folder. A shell link (shortcut) contains a command line to execute and sets the initial working directory, among other things.
By default for an all-users installation, 64-bit Python 3.10 is installed in “%ProgramFiles%\Python310”. By default for a per-user installation, it’s installed in “%LocalAppData%\Programs\Python\Python310”.