2012-03-27 107 views
4

我有以下代碼:蟒蛇os.path.realpath不能正常工作

os.chdir(os.path.dirname(os.path.realpath(__file__)) + "/../test") 
path.append(os.getcwd()) 
os.chdir(os.path.dirname(os.path.realpath(__file__))) 

哪些應該增加/../test到Python路徑,它這樣做,它全部採用PyDev的平穩運行之後的月食。

但是,當從控制檯第二os.chdir我午餐相同的應用程序做錯了事,實際上是錯誤的事情是os.path.realpath(__file__) CUS它的../originalFolder/myFile.py代替返回../test/myFile.py。當然,我可以通過使用固定的os.chdir("../originalFolder")來解決這個問題,但這對我來說似乎有點不對勁,但這對於日食和控制檯都有效。

P.S.我使用os.getcwd()實際上是因爲我想確保沒有這樣的文件夾已經添加,否則我不必切換目錄的

那麼,我的方法有什麼問題,或者我已經搞砸了嗎? ?或者是什麼? :)

在此先感謝! :)

回答

6

看看什麼是價值__file__。它不包含腳本的絕對路徑,它是來自命令行的值,所以它可能類似於「./myFile.py」或「myFile.py」。此外,realpath()不會使路徑成爲絕對路徑,因此在不同目錄中調用的realpath(「myFile.py」)仍將返回「myFile.py」。

我認爲你應該做ssomething這樣的:

import os.path 

script_dir = os.path.dirname(os.path.abspath(__file__)) 
target_dir = os.path.join(script_dir, '..', 'test') 
print(os.getcwd()) 
os.chdir(target_dir) 
print(os.getcwd()) 
os.chdir(script_dir) 
print(os.getcwd()) 

在我的電腦(Windows)中我已經導致這樣的:

e:\parser>c:\Python27\python.exe .\rp.py 
e:\parser 
e:\test 
e:\parser 

e:\parser>c:\Python27\python.exe ..\parser\rp.py 
e:\parser 
e:\test 
e:\parser 

注:如果您關心的兼容性(你不喜歡奇怪的路徑錯誤),每當你合併路徑時,你應該使用os.path.join()

注:我知道我的解決方案非常簡單(記住絕對路徑),但有時候最簡單的解決方案是最好的。

+3

'realpath()'使路徑絕對 – 2013-02-18 07:20:24

+0

[Here](http://helpful.knobs-dials.com/index.php/Python_usage_notes/Filesystem_stuff)是哪個命令做了什麼的一個很好的總結。 – 2013-02-18 07:27:05

+0

雖然這不是這個topi最流行的問題,但這個答案是最正確的。謝謝 ! – egelev 2015-06-25 11:40:47