user3299288 - 9 months ago 48
Python Question

# Python use of ~ versus python-path methods

Can someone explain what is the difference in using
filepath = 'C:/Users/your_name/Documents/subfolder/'
to
filepath = '~/Documents/subfolder/'
?

I am writing code that I'd like to be re-useable on a second computer with an identical folder structure, but different location of the Documents folder.

The following pages on SO appear to give indications on how to do it differently, but I'm wondering about how much better these are versus the method shown above. From an SO/Google point of view, searching for "~" has not lead to any useful answers either.

How to get an absolute file path in Python

Relative imports for the billionth time

Find current directory and file's directory

Answer Source

If the path is the same past the user name, then ~ would be best, you just have to make sure that you expand it before passing to routines that expect abs path.

In general ~ is just an environment variable to the user home directory that is currently in session, and to expand it just call something like: os.path.expandvars("~\your\tilde\path")