Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธี Force Write ไฟล์ลง Disk ด้วย File Descriptor ใน Python

ใช้ fdatasync(fd) บังคับเขียนไฟล์ลงดิสก์ (ไม่รวม metadata) ใช้ได้เฉพาะ Unix แพลตฟอร์มข้ามได้ ใช้ fsync(fd) (Unix เรียก fsync() Windows เรียก _commit())

ตัวอย่าง

import os, sys
fd = os.open("foo.txt", os.O_RDWR | os.O_CREAT)
os.write(fd, "This is test")
os.fsync(fd)  # บังคับเขียนลงดิสก์
os.lseek(fd, 0, 0)
str = os.read(fd, 100)
print("Read String is:", str)
os.close(fd)

ผลลัพธ์

Read String is: This is test