[英]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. 我已经将python文件和'g1.txt'放在同一目录中。 The code runs correctly when I don't use SublimeREPL 当我不使用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 它将脚本的目录附加到g1.txt
Expanding on this answer , SublimeREPL is not necessarily using the same working directory that g1.txt
is in. You can either use 扩展这个答案 ,SublimeREPL不一定使用相同的工作目录g1.txt
是,你可以使用
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: 您应该改用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
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. 将文件保持打开状态通常不是一个好主意,特别是如果您正在写文件时,因为程序结束时它们可能处于不确定状态。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.