【python】确保文件写入结束

本文探讨了在Python中如何确保文件数据能完全写入磁盘的问题。文章指出了使用`file.flush()`和`os.fsync()`组合的重要性,并提供了一个示例代码来演示如何避免因缓存而导致的数据丢失。

今天遇到了个问题:

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

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();

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值