Python os.fsync() - 强制写入与给定文件描述符相关的文件

Python os.fsync()

Python os.fsync()方法用于强制写入与给定文件描述符相关的文件

在这种情况下,我们使用的是一个文件对象(比如f)而不是一个文件描述符,那么我们需要使用 f.flush () 然后os.fsync(f.fileno())确保所有与文件对象f相关联的缓冲区都写到磁盘。

语法:os.fsync(fd)

参数:

fd:需要进行缓冲区同步的文件描述符。

返回类型:此方法不返回任何值。

示例1

使用 os.fsync() 方法

# Python program to explain os.fsync() method
   
# importing os module
import os
 
 
# File path
path = 'file.txt'
 
# Open the file and get
# the file descriptor
# associated with
# using os.open() method
fd = os.open(path, os.O_RDWR)
 
 
# Write a bytestring
str = b"GeeksforGeeks"
 
os.write(fd, str)
 
 
# The written string is
# available in program buffer
# but it might not actually
# written to disk until
# program is closed or
# file descriptor is closed.
 
# sync. all internal buffers
# associated with the file descriptor
# with disk (force write of file)
# using os.fsync() method
os.fsync(fd)
print("Force write of file committed successfully")
 
# Close the file descriptor
os.close(fd)

输出:

Force write of file committed successfully

示例2

如果处理文件对象。

# Python program to explain os.fsync() method
   
# importing os module
import os
 
 
# File path
path = 'file.txt'
 
# Open the file and get
# the file object
# using open() method
f = open(path, 'w')
 
 
# Write a string to
# the file object
str = "GeeksforGeeks"
f.write(str)
 
 
# Firstly, flush internal buffers
f.flush()
 
# Now, sync. all internal buffers
# associated with the file object
# with disk (force write of file)
# using os.fsync() method
os.fsync(f.fileno())
 
print("Force write of file committed successfully")
 
# Close the file object
f.close()

输出:

Force write of file committed successfully

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程