2010-06-01 100 views
11

我正在運行Mac OS X環境,並習慣於使用〜/來提供對當前用戶目錄的訪問。在Python中訪問相對路徑

例如,在我的Python腳本,我只是想用

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

但是想用

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

我得到一個試圖在沒有這樣的文件或目錄錯誤運行這個。有任何想法嗎?

回答

15

你需要在當前工作目錄使用os.path.expanduser(path)

os.chdir("~/Desktop/testdir/")正在尋找一個名爲「〜」。

還要注意該功能的文檔 - 特別是您需要正確設置$HOME環境變量以確保擴展發生。大多數情況下,這不會是一個問題,但如果擴展沒有發生,那就是可能的原因。

+0

我不知道那個! +1 – 2010-06-01 22:41:40

+1

非常酷,我該如何正確使用它? 「路徑」應該是「/ Desktop/testdir」嗎?我該如何切換到該目錄。非常感謝。 – Aaron 2010-06-01 23:03:52

+0

只需將它嵌入到您現有的chdir調用中,如下所示:os.chdir(os.path.expanduser(「〜/ ...」)) – 2010-06-01 23:26:31

2

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

os.path.expanduser(path) 

將擴大〜來是如果它被定義用戶的主目錄。

+0

我試過os.path.expanduser(「/ Desktop/testdir」),它告訴我沒有這樣的文件或目錄:'/ Desktop/test /'你知道我可能會做錯什麼嗎?最終我想chdir到〜/ Desktop/testdir – Aaron 2010-06-01 23:27:59

+0

os.path.expanduser(「〜/ Desktop/testdir」)是你需要的,就像Dan Head所說的那樣,這依賴於$ HOME的設置。 – Tyler 2010-06-01 23:34:19