原子写入到Python文件 [英] atomic writing to file with Python
问题描述
open(file,'w')使用Python将大块文本写入文件中).write(text)
如果脚本中断,文件写入不完成我想没有文件而不是部分完整的文件。可以这样做吗?
将数据写入临时文件,当数据成功写入时,将文件重命名为正确目的地文件例如
$ $ p $ $ $ $ $ $ $ b#确保所有数据都在磁盘
#请参阅http://stackoverflow.com/questions/7433057/is-rename-without-fsync-safe
f.flush()
os.fsync(f.fileno())
f.close()
$ b $ os.rename(tmpFile,myFile)
根据文档 http: //docs.python.org/library/os.html#os.rename
如果成功,重命名将会是一个原子操作(这是
POSIX要求)。在Windows上,如果dst
已经存在,则OSError将被提升
,即使它是一个文件;当
dst命名现有文件时,可能没有
方法来实现原子重命名。
p>
如果src和dst位于不同的文件系统上,那么操作可能会失败。
注意: 如果src和dest位置不在同一个文件系统上,它可能不是原子操作。
os.fsync
如果性能/响应比在电源故障,系统崩溃等情况下的数据完整性更重要,那么可以跳过这一步。
I am using Python to write chunks of text to files in a single operation:
open(file, 'w').write(text)
If the script is interrupted so a file write does not complete I want to have no file rather than a partially complete file. Can this be done?
Write data to a temporary file and when data has been successfully written, rename the file to the correct destination file e.g
f = open(tmpFile, 'w')
f.write(text)
# make sure that all data is on disk
# see http://stackoverflow.com/questions/7433057/is-rename-without-fsync-safe
f.flush()
os.fsync(f.fileno())
f.close()
os.rename(tmpFile, myFile)
According to doc http://docs.python.org/library/os.html#os.rename
If successful, the renaming will be an atomic operation (this is a POSIX requirement). On Windows, if dst already exists, OSError will be raised even if it is a file; there may be no way to implement an atomic rename when dst names an existing file
also
The operation may fail on some Unix flavors if src and dst are on different filesystems.
Note:
It may not be atomic operation if src and dest locations are not on same filesystem
os.fsync
step may be skipped if performance/responsiveness is more important than the data integrity in cases like power failure, system crash etc
这篇关于原子写入到Python文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!