简体   繁体   中英

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

I have put the python file and 'g1.txt' in the same directory. The code runs correctly when I don't use 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'

try this:

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

it will append the script's directory to g1.txt

Expanding on this answer , SublimeREPL is not necessarily using the same working directory that g1.txt is in. You can either use

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

as previously suggested, or the following will also work:

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

Just a minor thing, but you also don't close your file descriptor. You should use the with open() format instead:

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

This will automatically close the file descriptor when you're done with it, so you don't have to worry about closing it manually. Leaving files open is generally a bad idea, especially if you're writing to them, as they can be left in an indeterminate state when your program ends.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM