I discovered that a script's "current working directory" is, initially, not the where the script is located, but rather where the user is when he/she runs the script.
If the script is at /Desktop/Projects/pythonProject/myscript.py
, but I'm at /Documents/Arbitrary
in my terminal when I run the script, then that's going to be it's present working directory, and an attempt at open('data.txt')
is going to give File Not Found because it's not looking in the right directory.
So how is a script supposed to open files if it can't know where it's being run from? How is this handled?
My initial thought was to use absolute paths. Say my script needs to open data.txt
which is stored alongside it in its package pythonProject
. Then I would just say open('/Desktop/Projects/pythonProject/data.txt')
.
But then you can't ever move the project without editing every path in it, so this can't be the right solution.
Or is the answer simply that you must be in the directory where the script is located whenever you run the script? That doesn't seem right either.
Is there some simple manipulation for this that I'm not thinking of? Are you just supposed to os.chdir
to the script's location at the beginning of the script?