最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【整理】Python中写完文件再关闭后,不知道需要sleep多长时间才是安全的(才能保持数据真正写入了)

Python crifan 4845浏览 0评论

【问题】

有人遇到类似问题:

python,用:

rs=open(‘filename’,‘w')

打开文件后,然后写入一定量的数据,再去关闭:

rs.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.

Note

flush() 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.

所以,相关的,正确的,完整的代码,就是:

import 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 safe
fileObj.close();

 

【总结】

写python代码(和之前任何语言代码)之前,都还是需要了解相关的,所处理的问题的所属领域,所涉及的背景知识,才能真正写好程序的。

转载请注明:在路上 » 【整理】Python中写完文件再关闭后,不知道需要sleep多长时间才是安全的(才能保持数据真正写入了)

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
84 queries in 0.158 seconds, using 22.06MB memory