tags:

views:

40

answers:

2

Hi, 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?

+2  A: 

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.

Dan Head
I didn't know about that one! +1
Chinmay Kanchi
Very cool, how do I actually use this properly? Is the "path" supposed to be "/Desktop/testdir"? And how do I actually change to that directory. Thanks so much.
Aaron
Just nest it inside your existing chdir call like so: os.chdir(os.path.expanduser("~/..."))
Dan Head
That was much easier than I was trying to make it. Thanks again for the help.
Aaron
+1  A: 

From http://docs.python.org/library/os.path.html

os.path.expanduser(path)

Will expand ~ to being the users home directory if it is defined.

Tyler
I tried os.path.expanduser("/Desktop/testdir") and it is telling me no such file or directory: '/Desktop/test/' Do you know what I might be doing wrong? Ultimately I would like to chdir to ~/Desktop/testdir
Aaron
os.path.expanduser("~/Desktop/testdir") is what you would need, as Dan Head mentioned, this relies on $HOME being set.
Tyler