You can use os.chdir()
, but it's still a somewhat fragile approach - it's generally good practice to use absolute paths. For example, if you end up calling other code which changes your current working directory (which would be a bit of a naughty thing to do, but you can't rely on third party code to be perfect) then you'll end up with some subtle bugs that may be hard to track down.
Using absolute paths everywhere is generally not too tedious if you can pick a base directory that everything else can be relative to. Then your code ends up looking like:
with open(os.path.join(BASEDIR, "dir1", "dir2", "file.ext")) as fd:
# ... do stuff
That's not too tedious, is it?
One choice of base directory is to use the __file__
of your source file as Hansel suggests. This is fine if your data file is always in the same place, but if you ever decide to distribute your script then it'll probably end up in a different location. There are other approaches, but it depends what you need.