【python】确保文件写入结束
2016-11-23 21:30
141 查看
今天遇到了个问题:
我在执行如下代码时发现,文件只写了一半。也就是说,当文件量过大时,下面的代码是不能保证文件被正确写入的。
解决办法:
来源:http://www.crifan.com/python_after_write_file_then_do_not_know_how_long_to_sleep_is_safe_close/
1.实际上,这个问题,是涉及到文件的缓存,操作系统的缓存方面的内容。
而对此,文件级别的缓存,已经有对应的函数:
去保证数据的写回了.
2.而且另外,上面也提到了,如果想要真正能够确保数据的确已经写回了,可以使用:
所以,相关的,正确的,完整的代码,就是:
我在执行如下代码时发现,文件只写了一半。也就是说,当文件量过大时,下面的代码是不能保证文件被正确写入的。
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.
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.
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中文写入文件问题
- Python学习--文件和存储器的写入和读出实例
- 去除文件中的重复元素后写入文件 分类: python 小练习 open()文件读写 2013-12-03 11:21 356人阅读 评论(0) 收藏
- C语言循环输入字符串#结束写入文件
- python给文件写入/追加内容时输出x00和乱码的问题
- 【整理】Python中,添加写入数据到已经存在的Excel的xls文件,即打开excel文件,写入新数据
- python开发_搜索本地文件信息写入文件
- python文件的写入
- Python 获取接口数据,解析JSON,写入文件
- numpy数组与python的list互转,然后用json写入文件与c交互
- python readlines() 读文件,行结束符处理
- 确保多个进程同时写入同一个文件成功(php)
- python 如何把 utf - 8 字符串写入文件中_心若止水_百度空间
- 使用Python读取和写入mp3文件的id3v1信息
- python 文件结束
- python Debug 文件结束
- python实例26[将log同时写入文件和显示到UI的控件中]
- python csv文件写入
- Python写入文件,但是发现文件为空,竟然未写入!
- python实例26[将log同时写入文件和显示到UI的控件中]