即使我使用f.close,python也不会写
我试图编写一些代码,将一些文本输出到列表中。输出是一个变量,它是一个字符串,是要写入的文件的名称。但是,每当我查看文件时,都不会写入任何内容即使我使用f.close,python也不会写,python,file,io,Python,File,Io,我试图编写一些代码,将一些文本输出到列表中。输出是一个变量,它是一个字符串,是要写入的文件的名称。但是,每当我查看文件时,都不会写入任何内容 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')
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()
程序看起来正常,检查输出是否设置为正常,我将其设置为一个伪文件名,它工作了,假定打开后块内的代码没有编译器/解释器错误。输出文件应位于源所在的同一目录中
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()
您不应该添加
f.close()
,因为with
语句将为您完成此操作。另外,确保不要在别处用“代码>打开”(输出,“W”)<代码>重新打开文件,因为这会擦除文件。你可以共享你的整个代码吗?你的语句无论如何都关闭了在范围出口上的文件。在这个过程中,您可能会发现问题所在。@CodieCodeMonkey的意思是,您可以删除f.close()
,因为它包含在中。同时,您是否尝试过简化逻辑,让写操作正常工作?因此,注释掉所有的条件逻辑,然后简单地f.write(“Something”+str(node.cargo))
并证明您可以完成简单的编写。然后从这里开始,什么是“输出”?它是文件名吗?是否检查了open()调用引发的异常?运行程序时是否创建了文件(即使长度为零)?Sean没有说明确切的问题是什么,尽管我想知道它是否与存储在output