Sometimes, we want to get the home directory in Python in a cross-platform way.
In this article, we’ll look at how to get the home directory in Python in a cross-platform way.
What is the correct cross-platform way to get the home directory in Python?
To get the home directory in Python in a cross-platform way, we can use the pathlib module.
For instance, we write:
from pathlib import Path
home = str(Path.home())
print(home)
to call Path.home to return the home directory value as an object.
Then we can convert it to a string with str and return it.
Therefore, home is something like '/home/runner'.
Conclusion
To get the home directory in Python in a cross-platform way, we can use the pathlib module.