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

2024-09-30 04:40:38 发布

您现在位置: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()

当第二次使用变量(而不是用于在写入模式下打开文件的变量)执行读取时,它将返回一个空字符串

我知道,当第二次读取同一个文件时,它返回一个空字符串。但是为什么第一种情况下的代码返回正确的输出呢

有人能对此做出适当的解释吗


Tags: 文件ofhelloworldcloseread模式open
2条回答

首先要了解的是,当您执行textFile.write时,无法确定会立即写入文件。这是为了提高写入效率,首先将数据放入缓冲区,只有当文件已满、调用flush或文件关闭(内部执行flush)时,缓冲区才会写入文件

(从技术上讲,flush不足以确保将数据写入文件,请参见os.fsync

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

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

另外,在处理文件时,应该使用with open习惯用法:link

请参见下文,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()

相关问题 更多 >

    热门问题