Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 为什么可以';我不能在python 3中写入文件吗?_Python 3.x - Fatal编程技术网

Python 3.x 为什么可以';我不能在python 3中写入文件吗?

Python 3.x 为什么可以';我不能在python 3中写入文件吗?,python-3.x,Python 3.x,当我跑步时 Text = "Hello" newFileName = (input("What would you like to name this file? ")) newFile = open(newFileName, 'w') newFile.write(Text) print("Saved as ", newFileName, "!") 这就是文件。但是,该文件是空的。有人知道这里出了什么问题吗?您必须关闭file对象newFile,否则调用newFile.write()时实际写入

当我跑步时

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

这就是文件。但是,该文件是空的。有人知道这里出了什么问题吗?

您必须关闭file对象
newFile
,否则调用
newFile.write()
时实际写入的缓冲区可能无法刷新到磁盘上的实际文件。也就是说,在末尾添加这一行:

newFile.close()
Python有一个很好的结构来处理这种“设置和分解”逻辑,即
with
语句所使用的。使用此选项,您可以将代码更改为

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, "!")

<> > <>代码> 块,文件即使在中间发生错误,也会自动关闭。p> 对我来说它不是空的,你能写下你输入的具体内容吗?也更喜欢将open(newFileName,'w')作为f:使用,因为它处理关闭文件等操作。