我有点困惑,为什么以下代码段在第二次读取同一文件时返回正确的输出:
textCont = "Hello World"
print("Original content of the file")
print(open(filename).read())
textFile = open(filename, "w")
textFile.write(textCont)
print("New file content:")
textFile = open(filename)
print(textFile.read())
textFile.close()
其中filename是包含一些现有数据的文件。该文件将被读取、重写,然后再次读取
在上述情况下,相同的变量用于在写入模式下打开文件,然后在读取模式下打开文件。这可以正常工作,并在第二次读取时提供正确的输出(显示覆盖前一次的内容)
但以下版本的代码不起作用:
textCont = "Hello World"
print("Original content of the file")
print(open(filename).read())
textFile = open(filename, "w")
textFile.write(textCont)
print("New file content:")
textFile_1 = open(filename)
print(textFile_1.read())
textFile.close()
textFile_1.close()
当第二次使用变量(而不是用于在写入模式下打开文件的变量)执行读取时,它将返回一个空字符串
我知道,当第二次读取同一个文件时,它返回一个空字符串。但是为什么第一种情况下的代码返回正确的输出呢
有人能对此做出适当的解释吗
首先要了解的是,当您执行textFile.write时,无法确定会立即写入文件。这是为了提高写入效率,首先将数据放入缓冲区,只有当文件已满、调用flush或文件关闭(内部执行flush)时,缓冲区才会写入文件
(从技术上讲,flush不足以确保将数据写入文件,请参见os.fsync)
因此,原因是不能使用两个不同的变量名称,因为写入操作从未真正发生在
textFile_1.close()
行之前它使用相同的变量名“工作”的原因是,当您重新绑定
textFile = open(filename)
时,以前绑定到textFile
的文件现在不在任何地方引用,因此垃圾收集器将其删除。当文件句柄被删除时,数据将写入文件,因此您可以在以后读取它另外,在处理文件时,应该使用with open习惯用法:link
请参见下文,FileDebug包装器将显示文件何时被删除,以及数据何时被写入
由于@Stefan,第二个案例中的问题得到了解决
解决方案是在写入文件之后,但在再次读取之前关闭该文件
相关问题 更多 >
编程相关推荐