即使我使用f.clos,python也不会写

2024-04-26 05:50:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我想写一些代码,输出一些文本到一个列表。output是一个变量,它是一个字符串,是要写入的文件的名称。然而,每当我看这个文件时,什么也没写。你知道吗

with open(output, 'w') as f:
        f.write("Negative numbers mean the empty space was moved to the left     and positive numbers means it was moved to the right" + '\n')
        if A == True:
           the_h = node.h
        elif A== False:
           the_h = 0
        f.write("Start  " + str(node.cargo) + "  " + str(node.f) +"  "     +str(the_h)+"  " + '\n')
        if flag == 0:
            flag = len(final_solution)
        for i in range (1,flag):
            node = final_solution[i]
            f.write(str(node.e_point - node.parent.e_point) + str(node.cargo) + "  " + str(node.f) +'\n')
f.close()

Tags: 文件thetonodeoutputifwritefinal
2条回答

您不应该添加f.close(),因为with语句可以帮您完成。还要确保不要在其他地方用open(output, 'w')重新打开该文件,因为那样会删除该文件。你知道吗

程序看起来正常,检查输出是否设置为正常,我设置为一个伪文件名,它工作,假设代码块内打开后没有编译器/解释器错误。输出文件应位于源所在的同一目录中。你知道吗

output = "aa.txt"
with open(output, 'w') as f:
        f.write("Negative numbers mean the empty space was moved to the left     and positive numbers means it was moved to the right" + '\n')
        if A == True:
           the_h = node.h
        elif A== False:
           the_h = 0
        f.write("Start  " + str(node.cargo) + "  " + str(node.f) +"  "     +str(the_h)+"  " + '\n')
        if flag == 0:
            flag = len(final_solution)
        for i in range (1,flag):
            node = final_solution[i]
            f.write(str(node.e_point - node.parent.e_point) + str(node.cargo) + "  " + str(node.f) +'\n')
f.close()

相关问题 更多 >