0

我已将 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'
4

2 回答 2

0

扩展这个答案,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

这将在您完成后自动关闭文件描述符,因此您不必担心手动关闭它。让文件保持打开状态通常是个坏主意,尤其是在您给它们写信时,因为当您的程序结束时,它们可能会处于不确定状态。

于 2013-10-02T13:51:35.180 回答
0

尝试这个:

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

它将脚本的目录附加到 g1.txt

于 2013-10-02T13:07:19.360 回答