2013-10-02 18 views
0

我已經把python文件和'g1.txt'放在同一個目錄下。 代碼運行正常,當我不使用SublimeREPLpython:IOError:[Errno 2]使用sublime時沒有這樣的文件或目錄REEL

def build_graph(file_name): 
    new_file = open(file_name, 'r') 
    n, m = [int(x) for x in new_file.readline().split()] 

    graph = {} 
    for line in new_file: 
     # u, v, w is the tail, head and the weight of the a edge 
     u, v, w = [int(x) for x in line.split()] 
     graph[(u, v)] = w 

    return n, graph 

if __name__ == '__main__': 
    print build_graph('g1.txt') 

>>> >>> Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "<string>", line 18, in <module> 
    File "<string>", line 6, in build_graph 
IOError: [Errno 2] No such file or directory: 'g1.txt' 

回答

0

試試這個:

import os 
build_graph(os.path.join(os.path.dirname(__file__),"g1.txt")) 

將追加腳本目錄以g1.txt

0

擴展在此answer,SublimeREPL是不一定使用與g1.txt相同的工作目錄。您可以使用

import os 
build_graph(os.path.join(os.path.dirname(__file__),"g1.txt")) 

如先前建議,或下面也將工作:

if __name__ == '__main__': 
    import os 
    os.chdir(os.path.dirname(__file__)) 
    print build_graph('g1.txt') 

只是一個次要的事情,但你也不要關閉您的文件描述符。您應該使用with open()格式來代替:

def build_graph(file_name): 
    with open(file_name, 'r') as new_file: 
     n, m = [int(x) for x in new_file.readline().split()] 

     graph = {} 
     for line in new_file: 
      # u, v, w is the tail, head and the weight of the a edge 
      u, v, w = [int(x) for x in line.split()] 
      graph[(u, v)] = w 

    return n, graph 

當你用它做這將自動關閉文件描述符,所以你不必擔心手動關閉它。保持文件打開通常是一個糟糕的主意,特別是在寫入文件時,因爲在程序結束時它們可能處於不確定狀態。

相關問題