Reputation: 3
I'm working on a project with a friend and we use different operating systems (Windows / MACOS) which we believe to be the root of this problem. The problem being that when reading a file we have different working directories, mine being one step deeper in the hierarchy.
My path: C:/Code-projects/Python/python-laborations/lab1
Whereas his is: C:/Code-projects/Python/python-laborations
(not exactly since he's on Mac but it's beside the point)
We want to access a file in the path C:/Code-projects/Python/python-laborations/data
. Later on we want to write to this directory as well.
Now when trying to read a file the following string works for him: 'data/tramstops.json'
but I'll get a FileNotFound error. Instead I need to use the path '../data/tramstops.json'
and everything works.
Our combined solution for this looks as follows, where path is for example 'data/tramstops.json'
:
try:
with open(path, 'r', encoding="utf-8") as file:
do_something()
except FileNotFoundError:
with open('../' + path, 'r', encoding="utf-8") as file:
do_something()
But now we want to write to a file and using this approach will not raise an exception but instead just create the file (in the wrong place). So we need a different solution. One thing we tried was constructing an absolute path with the os module. Pseudo-code as follows:
current_dir = os.getcwd()
split current_dir into list
if "lab1" in list then delete it
add path-argument to current_dir
This solution works but it's not very elegant and we feel there must be a better way. We also want to avoid hard-coding paths into our code since we don't want it to depend on file-structure. Is there a better way?
Upvotes: 0
Views: 963
Reputation: 28036
os.path
Instead of importing this module directly, import os and refer to
this module as os.path. The "os.path" name is an alias for this
module on Posix systems; on other systems (e.g. Mac, Windows),
os.path provides the same operations in a manner specific to that
platform, and is an alias to another module (e.g. macpath, ntpath).
Some of this can actually be useful on non-Posix systems too, e.g.
for manipulation of the pathname component of URLs.
Upvotes: 2