簡體   English   中英

python:IOError:[Errno 2]使用sublimeREPL時沒有此類文件或目錄

[英]python: IOError: [Errno 2] No such file or directory when use sublimeREPL

我已經將python文件和'g1.txt'放在同一目錄中。 當我不使用SublimeREPL時,代碼可以正確運行

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'

嘗試這個:

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

它將腳本的目錄附加到g1.txt

擴展這個答案 ,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

完成后,它將自動關閉文件描述符,因此您不必擔心手動關閉它。 將文件保持打開狀態通常不是一個好主意,特別是如果您正在寫文件時,因為程序結束時它們可能處於不確定狀態。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM