在python中第二次读取文件时出现问题



我有点困惑,为什么以下代码片段在第二次读取同一文件时返回正确的输出:

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不足以确保数据写入文件,请参阅os.fsync(

因此,原因是无法使用两个不同的变量名称,因为写入操作从未真正发生在textFile_1.close()行之前

原因是它";作品";具有相同变量名的是,当您重新绑定textFile = open(filename)时,以前绑定到textFile的文件现在在任何地方都没有被引用,因此垃圾收集器会将其删除。当删除文件句柄时,数据会写入文件,因此您可以在之后读取它。

此外,在处理文件时,您应该使用with open习语:链接

如下所示,FileDebug包装器将显示何时删除文件,以及何时写入数据。

class FileDebug:
def __init__(self, f, name):
self.f = f
self.name = name
def close(self):
print(f"Closing file (var: {self.name})")
self.f.close()
def write(self, *args, **kwargs):
self.f.write(*args, **kwargs)
def read(self, *args, **kwargs):
return self.f.read(*args, **kwargs)
def __del__(self):
print(f"Del completed (var: {self.name})")
filename = "text.txt"
def different_name():
textCont = "Hello World"
print("Original content of the file")
print(FileDebug(open(filename), "No name").read())
textFile = FileDebug(open(filename, "w"), "textFile")
textFile.write(textCont)
print("New file content:")
textFile_1 = FileDebug(open(filename), "textFile_1")
print(textFile_1.read())
textFile.close()
textFile_1.close()
def same_name():
textCont = "Hello World"
print("Original content of the file")
print(FileDebug(open(filename), "No name").read())
textFile = FileDebug(open(filename, "w"), "textFile")
textFile.write(textCont)
print("New file content:")
textFile = FileDebug(open(filename), "textFile")
print(textFile.read())
textFile.close()

different_name()
"""
Original content of the file
Del completed (var: No name)
New file content:
Closing file (var: textFile)
Closing file (var: textFile_1)
Del completed (var: textFile)
Del completed (var: textFile_1)
"""
#same_name()
"""
Original content of the file
Del completed (var: No name)
New file content:
Del completed (var: textFile) # the file is closed and the data is written
Hello World
Closing file (var: textFile)
Del completed (var: textFile)
"""

多亏了@Stefan,第二个案例中的问题得到了解决。

解决方案是在写入后关闭文件,然后再读取。

print(open(filename).read())
textFile = open(filename, "w")
textFile.write(textCont)
textFile.close() // close the file from write mode before reading it again
print("your file content:")
textFile_1 = open(filename)
print(textFile_1.read())
textFile_1.close()

最新更新