Python – Accessing Relative Path

pathpython

I'm running a Mac OS X environment and am used to using ~/ to provide the access to the current user's directory.

For example, in my python script I'm just trying to use

os.chdir("/Users/aaron/Desktop/testdir/")

But would like to use

os.chdir("~/Desktop/testdir/")

I'm getting a no such file or directory error when trying to run this. Any ideas?

Best Answer

You'll need to use os.path.expanduser(path)

os.chdir("~/Desktop/testdir/") is looking for a directory named "~" in the current working directory.

Also pay attention to the documentation of that function - specifically that you'll need the $HOME environment variable set properly to ensure that the expansion takes place. Most of the time this wont be a problem but if the expansion doesn't take place, that's the likely reason.

Related Question