Python 中的 file.flush() 与 os.fsync()

    xiaoxiao2025-06-13  13

    在Python 官方文档https://docs.python.org/2/library/stdtypes.html?highlight=file%20flush#file.flush 关于file.flush() 的说明中写道:“ flush() does not necessarily write the file’s data to disk. Use flush() followed by os.fsync() to ensure this behavior.”flush方法并不强制把数据写入到磁盘文件中,那么flush方法为什么会这样呢? 其实这里有两种层面的buffering: 1. Internal buffers 2. Operating system buffers Internal buffers 创建在 runtime/library/language 中避免每次写操作都调用系统call,依次来加速运行。当需要把数据写入文件时,先写入internal buffer, 当internal buffer 溢满时,再调用系统call写入到文件中。 所以为了确保数据写入到了文件中,file.flush() 之后要调用os.fsync()。

    Example

    #!/usr/bin/python import os, sys # Open a file fd = os.open( "foo.txt", os.O_RDWR|os.O_CREAT ) # Write one string os.write(fd, "This is test") # Now you can use fsync() method. # Infact here you would not be able to see its effect. os.fsync(fd) # Now read this file from the beginning os.lseek(fd, 0, 0) str = os.read(fd, 100) print "Read String is : ", str # Close opened file os.close( fd ) print "Closed the file successfully!!"

    Reference: http://stackoverflow.com/questions/7127075/ http://www.tutorialspoint.com/python/os_fsync.htm

    转载请注明原文地址: https://ju.6miu.com/read-1299917.html
    最新回复(0)