'How to handle paths and working directory in Python
I have the following folder structure:
- Project
- Main Folder
- Module.py
- Other Folders
- blah.py
Launching the following code from the module Module.py provides two ways to get the working directory and it seems that they are equivalent:
pathlib.Path(__file__).parent.resolve()
pathlib.Path.cwd()
What are the differences (pros & cons) in using one way over the other?
Solution 1:[1]
Surprisingly they are pretty much the same.
If you check the source code of pathlib. You can see pathlib.Path.cwd() just returns os.
def cwd(cls):
"""Return a new path pointing to the current working directory
(as returned by os.getcwd()).
"""
return cls(os.getcwd())
And pathlib.Path(__file__).parent.resolve() the same with some additional validations.
def resolve(self, path, strict=False):
s = str(path)
if not s:
return os.getcwd()
previous_s = None
if _getfinalpathname is not None:
if strict:
return self._ext_to_normal(_getfinalpathname(s))
else:
tail_parts = [] # End of the path after the first one not found
while True:
try:
s = self._ext_to_normal(_getfinalpathname(s))
except FileNotFoundError:
previous_s = s
s, tail = os.path.split(s)
tail_parts.append(tail)
if previous_s == s:
return path
else:
return os.path.join(s, *reversed(tail_parts))
# Means fallback on absolute
return None
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | 2f0AX4XfWiT6HUe |
