繁体   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