2014-11-02 29 views
0

失敗,我把一個文本文件,它包括了Python文件的文件夾外,即在父目錄訪問文本文件在Ubuntu

a.txt 
folder 
    myPython.py 

以下是我用

for line in open('../a.txt','rb'): 
    print line 

的代碼我在Windows上運行良好,但說

IOError: [Errno 2] No such file or directory: '../a.txt' 

在Ubuntu 12.10中,是否有任何問題的規範的路徑?

更新 它的工作原理,當我使用

fn = os.path.join(os.path.dirname(__file__), '../a.txt') 
for line in open(fn,'rb'): 
     print line 

我很好奇,爲什麼這是可能的..

+0

你肯定有文件?它在Ubuntu上爲我工作。 – ChillarAnand 2014-11-02 12:49:33

+0

它也適用於我。 – badc0re 2014-11-02 12:50:27

+0

@ChillarAnand謝謝,我更新了一個工作場景的問題..我在Python 2.7中使用Ubuntu 12.10,是嗎? – william007 2014-11-02 12:52:18

回答

0

好吧,我弄明白這個問題:open() can't find file given path relative to PYTHONPATH

「」打開相對於當前目錄...當前目錄默認爲,無論它在命令行上啓動python時是什麼「」

當我更改目錄(cd)到文件夾級別,它適用於

for line in open('../a.txt','rb'): 
    print line 
+0

這不是特定於Python的,這是幾乎所有程序的工作原理......您可以從sys.argv [0]中獲得腳本所在的目錄, – Carpetsmoker 2014-11-02 13:00:48