Looking through the new pathlib
module in Python 3.4, I notice that there isn't any simple way to get the user's home directory. The only way I can come up with for getting a user's home directory is to use the older os.path
lib like so:
import pathlib from os import path p = pathlib.Path(path.expanduser("~"))
This seems clunky. Is there a better way?
Use os module to get the Home Directorypath. expanduser('~') to get the home directory in Python. This also works if it is a part of a longer path like ~/Documents/my_folder/. If there is no ~ in the path, the function will return the path unchanged.
Create Directory in Python Using the Path. mkdir() Method of the pathlib Module. The Path. mkdir() method, in Python 3.5 and above, takes the path as input and creates any missing directories of the path, including the parent directory if the parents flag is True .
The pathlib is a Python module which provides an object API for working with files and directories. The pathlib is a standard module. Path is the core object to work with files.
parts : returns a tuple that provides access to the path's components. name : the path component without any directory. parent : sequence providing access to the logical ancestors of the path. stem : final path component without its suffix.
As of python-3.5, there is pathlib.Path.home()
, which improves the situation somewhat.
The result on Windows is
>>>pathlib.Path.home() WindowsPath('C:/Users/username')
and on Linux
>>>pathlib.Path.home() PosixPath('/home/username')
There is method expanduser()
:
p = PosixPath('~/films/Monty Python') p.expanduser() PosixPath('/home/eric/films/Monty Python')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With