开发者

Accessing relative path in Python

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 开发者_JS百科run this. Any ideas?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜