python,用:?1rs=open(‘filename’,‘w')打开文件后,然后写入一定量的数据,再去关闭:?12rs.close()sleep(5)但是问题在于,每次写入文件的数据,是不固定的,所以,不知道sleep多长时间,才能确保真正数据已经写入了。 【解决过程】1.实际上,这个问题,是涉及到文件的缓存,操作系统的缓存方面的内容。而对此,文件级别的缓存,已经有对应的函数:file.flush()Flush the internal buffer, like stdio‘s fflush(). This may be a no-op on some file-like objects.Noteflush() does not necessarily write the file’s data to disk. Use flush() followed by os.fsync() to ensure this behavior.去保证数据的写回了.2.而且另外,上面也提到了,如果想要真正能够确保数据的确已经写回了,可以使用:os.fsync(fd)Force write of file with filedescriptor fd to disk. On Unix, this calls the native fsync() function; on Windows, the MS _commit() function.If you’re starting with a Python file object f, first do f.flush(), and then do os.fsync(f.fileno()), to ensure that all internal buffers associated with f are written to disk.Availability: Unix, and Windows starting in 2.2.3.所以,相关的,正确的,完整的代码,就是:?12345678910import os; fileObj=open('filename', 'w');#write data into fileObj here#first do file flush()fileObj.flush();#then os fsync()os.fsync(fileObj);#then close is safefileObj.close();
python 写入文件
最新推荐文章于 2024-04-03 16:50:25 发布