【问题标题】:Python question about write() and truncate()关于 write() 和 truncate() 的 Python 问题
【发布时间】:2011-04-09 18:56:43
【问题描述】:

我在 Mac 上的终端中,正在学习如何打开、关闭、读取、删除文件。

当我设置时

f = open("sample.txt", 'w')

然后点击f.truncate()删除内容。

但是,当我执行f.write() 时,它不会在文本文件中更新。它只会在我做f.truncate() 之后更新。

我想知道为什么会发生这种情况(我认为f.truncate() 应该删除文本!)?为什么我输入f.write()时文本编辑器没有自动更新?

【问题讨论】:

    标签: python terminal


    【解决方案1】:

    f.write() 写入 Python 进程自己的缓冲区(类似于 C 中的 fwrite() 函数)。但是,直到您调用f.flush()f.close(),或者当缓冲区填满时,数据才会真正刷新到操作系统缓冲区中。执行此操作后,所有其他应用程序都可以看到数据。

    请注意,操作系统会执行另一层缓冲/缓存——由所有正在运行的应用程序共享。当文件被刷新时,它会被写入这些缓冲区,但直到经过一段时间或调用fsync() 后才会写入磁盘。如果您的操作系统崩溃或计算机断电,这些未保存的更改将会丢失。

    【讨论】:

    • 太好了,谢谢。另外,在我使用 write 函数后, truncate() 似乎没有删除内容。如何删除内容(我目前正在做的是关闭 python 并重新打开它以截断内容)??
    【解决方案2】:

    让我们看一个例子:

    import os
    # Required for fsync method: see below
    
    f = open("sample.txt", 'w+')
    # Opens sample.txt for reading/writing
    # File pointer is at position 0
    
    f.write("Hello")
    # String "Hello" is written into sample.txt
    # Now the file pointer is at position 5
    
    f.read()
    # Prints nothing because file pointer is at position 5 & there
    # is no data after that
    
    f.seek (0)
    # Now the file pointer is at position 0
    
    f.read()
    # Prints "Hello" on Screen
    # Now the file pointer is again at position 5
    
    f.truncate()
    # Nothing will happen, because the file pointer is at position 5
    # & the truncate method truncate the file from position 5.     
    
    f.seek(0)
    # Now the file pointer  at position 0
    
    f.truncate()
    # Trucate method Trucates everything from position 0
    # File pointer is at position 0
    
    f.write("World")
    # This will write String "World" at position 0
    # File pointer is now at position 5     
    
    f.flush()
    # This will empty the IOBuffer
    # Flush method may or may not work depends on your OS 
    
    os.fsync(f)
    # fsync method from os module ensures that all internal buffers
    # associated with file are written to  the disk
    
    f.close()
    # Flush & close the file object f
    

    【讨论】:

      【解决方案3】:

      出于性能原因,输出到文件是缓冲的。因此,除非您告诉它“现在将缓冲区写入磁盘”,否则数据可能直到稍后才真正写入文件。这通常使用flush() 完成。 truncate() 显然在截断之前刷新。

      【讨论】:

      • 太好了,谢谢。另外,在我使用 write 函数后, truncate() 似乎没有删除内容。如何删除内容(我目前正在做的是关闭 python 并重新打开它以截断内容)??
      • truncate() 默认截断到当前位置。尝试truncate(0) 将其完全清空。
      猜你喜欢
      • 1970-01-01
      • 2011-03-12
      • 1970-01-01
      • 2016-12-21
      • 1970-01-01
      • 2010-10-18
      • 2013-01-16
      • 1970-01-01
      相关资源
      最近更新 更多