Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Home Directory with pathlib

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?

like image 429
Alex Bliskovsky Avatar asked Apr 08 '14 20:04

Alex Bliskovsky


People also ask

How do I get the Python home path?

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.

How can we create a directory with the Pathlib module?

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 .

What does Pathlib path () do?

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.

What does Pathlib path return?

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.


2 Answers

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')  
like image 121
simon Avatar answered Sep 28 '22 11:09

simon


There is method expanduser():

p = PosixPath('~/films/Monty Python') p.expanduser() PosixPath('/home/eric/films/Monty Python') 
like image 22
宏杰李 Avatar answered Sep 28 '22 10:09

宏杰李