heyyy
heyyy

Reputation: 29

Understanding how `os.path.join` works with `os.path.expanduser`

What does this line of code mean

datafolder = os.path.join(os.path.expanduser("~"), "Data", "books")

Does this line create a folder called datafolder and if it does can I insert files into it and load a file through the line

!load getdata.py

Upvotes: 2

Views: 2147

Answers (1)

cs95
cs95

Reputation: 402423

From the docs:

os.path.expanduser(path)

On Unix and Windows, return the argument with an initial component of ~ or ~user replaced by that user‘s home directory.

In Unix, your home directory is represented by a tilde (~) sign. Using os.path.expanduser expands the tilde to the actual path:

In [765]: os.path.expanduser("~")
Out[765]: '/Users/Coldspeed'

This string, along with 'Data' and 'books', are joined together by os.path.join to form a fully qualified path:

In [766]: os.path.join(os.path.expanduser("~"), 'Data', 'books')
Out[766]: '/Users/Coldspeed/Data/books'

This is a convenient way to specify your home directory without having to hardcode it.

Upvotes: 4

Related Questions