码迷,mamicode.com
首页 > 编程语言 > 详细

【python】确保文件写入结束

时间:2016-11-23 22:24:38      阅读:237      评论:0      收藏:0      [点我收藏+]

标签:tor   led   pytho   write   native   function   tin   des   comm   

今天遇到了个问题:

我在执行如下代码时发现,文件只写了一半。也就是说,当文件量过大时,下面的代码是不能保证文件被正确写入的。

fd = open(test.txt,w)
fd.write("a lot of thing")
fd.close()

 

解决办法:

来源:http://www.crifan.com/python_after_write_file_then_do_not_know_how_long_to_sleep_is_safe_close/

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 doos.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】确保文件写入结束

标签:tor   led   pytho   write   native   function   tin   des   comm   

原文地址:http://www.cnblogs.com/dplearning/p/6095446.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!