文件写入与缓存

由于写入磁盘是一个比较耗时的操作,多次写入少量数据与一次写入大量数据相比,所需的时间更久,所以大部分程序在处理写入的时候都会将写入的数据进行缓存,等到缓存满了之后再写入磁盘,python在使用open打开文件进行写入时会自动进行缓存。

下面的代码,在程序运行开始后一段时间,只有写入的文件名,文件大小一直保持为0

import time


with open("/home/buxizhizhoum/test_cp.py", "wb") as f:
    i = 0
    while True:
        i += 1
        f.write(str(i))  # only write data to buffer
        print i
        time.sleep(1)

原因在于使用f.write()只是将数据写入缓存,并不能保证数据已经被写入磁盘,当缓存满时,Python会将缓存的数据写入磁盘。

如果需要强制在写入缓存后立即写入磁盘,可以使用f.flush(),但是使用f.flush()还是不能确保数据一定写入了磁盘,因为还有可能被操作系统缓存,这时可以使用os.fsync(f)告诉操作系统将数据写入磁盘。

import time
import os


with open("/home/buxizhizhoum/test_cp.py", "wb") as f:
    i = 0
    while True:
        i += 1
        f.write(str(i))
        f.flush()  # flush to buffer, the possibility that data mighted be buffered by OS is still exist.
        os.fsync(f)  # write to disk immediately
        print i
        time.sleep(1)

此外可以在打开文件时,传参数告诉python不缓存任何数据,直接将数据写磁盘,这时可以使用open("filename", "w", 0),或者只缓存一行数据open("filename", "w", 1)

with open("/home/buxizhizhoum/test_cp.py", "wb", 0) as f:  # not to buffer any data, by passing 0
    i = 0
    while True:
        i += 1
        f.write(str(i) + '
')
        print i
        time.sleep(1)

由于磁盘的随机读写比连续读写慢很多,这会拖慢对这个文件的所有操作。

ref: https://stackoverflow.com/questions/9824806/how-come-a-file-doesnt-get-written-until-i-stop-the-program

原文地址:https://www.cnblogs.com/buxizhizhoum/p/8623808.html