为什么我无法在python 3中写入文件?

时间:2018-09-25 17:57:20

标签: python-3.x

我跑步时

class PostDelete(LoginRequiredMixin, generic.DeleteView):

它使文件。但是该文件为空。有人知道这是怎么回事吗?

1 个答案:

答案 0 :(得分:1)

您必须关闭文件对象newFile,否则调用newFile.write()时实际上要写入的缓冲区可能不会刷新到磁盘上的实际文件。也就是说,在最后添加此行:

newFile.close()

Python有一个很好的结构来处理with语句使用的这种“设置和拆除”逻辑,称为context managers。使用此功能,您可以将代码更改为

Text = "Hello"
newFileName = input("What would you like to name this file? ")
with open(newFileName, 'w') as newFile:
    newFile.write(Text)
print("Saved as ", newFileName, "!")

完成with块后,即使中间发生某些错误,文件也会自动关闭。

相关问题