User home path in Matlab, Octave, and Python
The tilde “~” character is used by most terminal shells as shorthand for the user home directory.
The home directory is typically a safer place to write files than the system root directory, so ~ give a convenient way to refer to an absolute path generic across systems.
Many code languages require parsing the tilde, including Python, C++, Fortran and Matlab.
GNU Octave understands that ~
tilde is the user’s home directory on any operating system, even Windows.
Matlab does not consistently understand ~
as the user home directory, particularly on Windows.
The
stdlib for Matlab
has a function stdlib.expanduser()
that expands the
tilde character ~
to the user home directory
on all operating systems, including Windows.
stdlib.expanduser('~/Downloads/foo')
OS | expanded |
---|---|
Linux | /home/username/Downloads/foo |
Windows | C:/users/username/Downloads/foo |
macOS | /Users/username/Downloads/foo |
Python paths starting with ~ need pathlib.Path(’~/mypath’).expanduser() method to expand the ~ into the user home directory.
import pathlib
pathlib.Path('~/Downloads/foo').expanduser()
Related: CMake expanduser