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

在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

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值