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

时间:2015-09-04 02:45:27

标签: python file io

我试图编写一些代码,将一些文本输出到列表中。 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()

2 个答案:

答案 0 :(得分:0)

程序看起来没问题,检查输出是否设置好,我设置为虚拟文件名,它有效,假设打开后块内的代码没有编译器/解释器错误。输出文件应位于源所在的同一目录中。

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()

答案 1 :(得分:0)

您不应添加f.close(),因为with语句会为您执行此操作。另外,请确保不要使用open(output, 'w')重新打开文件,因为这会删除文件。