我把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'
答案 0 :(得分:0)
试试这个:
import os
build_graph(os.path.join(os.path.dirname(__file__),"g1.txt"))
它会将脚本的目录附加到g1.txt
答案 1 :(得分:0)
扩展此answer,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
这将在您完成后自动关闭文件描述符,因此您不必担心手动关闭它。保持文件打开通常是一个坏主意,特别是如果你正在写文件,因为当你的程序结束时它们可能会处于不确定的状态。