Python fsync() 方法强制将具有给定文件描述符的文件写入存储磁盘。如果我们正在使用 Python 文件对象(比如 f),则必须使用 f.flush() 方法,以便清除内部缓冲区。然后,使用 os.fsync(f.fileno()) 确保与文件对象关联的所有内部缓冲区都写入磁盘。
通常,每当我们将数据写入文件时,在写入磁盘之前,它都会存储在缓冲区中。然后,操作系统决定何时将此缓冲区写入磁盘。os.fsync() 方法在 “os.write()” 之后使用,以确保缓冲区中的所有数据都应立即写入磁盘。
语法
以下代码块显示了 fsync() 方法的语法 -
os.fsync(fd)
参数
Python os.fsync() 方法接受单个参数 -
- fd − 这是缓冲区同步所需的文件描述符。
返回值
Python os.fsync() 方法不返回任何值。
例在此示例中,我们打开具有读取和写入权限的给定文件的文件描述符。然后,我们将一个简单的字节字符串写入文件,并使用 os.fsync() 方法确保在关闭文件描述符之前将其写入磁盘。
#!/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, b"Welcome to qikepu")
# Now you can use fsync() method.
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!!")
当我们运行上述程序时,它会产生以下结果——
Read String is : b'Welcome to qikepu'
Closed the file successfully!!
Closed the file successfully!!
例
fsync() 方法可以引发 IOError 和 OSError 等异常。以下示例演示如何在 try-except-finally 块中处理这些异常。
import os
# write operation in try block
try:
# Open a file descriptor
fd = os.open('foo.txt', os.O_RDWR|os.O_CREAT)
# Write data to the file
os.write(fd, b"This is qikepu")
# Using os.fsync() method
os.fsync(fd)
# reading the file
os.lseek(fd, 0, 0)
str = os.read(fd, 100)
print ("Read String is : ", str)
except Exception as exp:
print(f"An error occurred: {exp}")
finally:
# closing file
os.close(fd)
print("File closed successfully!!")
当我们运行上述程序时,它会产生以下结果——
Read String is : b'This is qikepu'
File closed successfully!!
File closed successfully!!