Python中的OS模塊提供了與操作係統進行交互的函數。操作係統屬於Python的標準實用程序模塊。該模塊提供了使用依賴於操作係統的函數的便攜式方法。
os.fsync()
Python中的方法用於強製寫入與給定文件描述符關聯的文件。
如果我們正在使用文件對象(例如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 commited successfully")
# Close the file object
f.close()
輸出:
Force write of file committed successfully
相關用法
- Python next()用法及代碼示例
- Python os.dup()用法及代碼示例
- Python set()用法及代碼示例
- Python Decimal max()用法及代碼示例
- Python PIL ImageOps.fit()用法及代碼示例
- Python os.rmdir()用法及代碼示例
- Python sympy.det()用法及代碼示例
- Python Decimal min()用法及代碼示例
- Python os.readlink()用法及代碼示例
- Python os.writev()用法及代碼示例
- Python os.readv()用法及代碼示例
- Python PIL RankFilter()用法及代碼示例
- Python os.rename()用法及代碼示例
- Python os.sendfile()用法及代碼示例
注:本文由純淨天空篩選整理自ihritik大神的英文原創作品 Python | os.fsync() method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。