2 回答
TA贡献1796条经验 获得超7个赞
首先要了解的是,当您执行 textFile.write 时,不确定是否会立即写入文件。这是为了通过将数据首先放入缓冲区来提高写入效率,只有当缓冲区已满或调用刷新或文件关闭(内部执行刷新)时,缓冲区才会写入文件。
所以原因是不适用于两个不同的变量名称是因为写操作从未真正发生在该行之前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)
"""
TA贡献1831条经验 获得超4个赞
第二个案例中的问题得到了解决。
解决方案是在写入之后但再次读取之前关闭文件。
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()
添加回答
举报