我使用Python在一个操作中将文本块写入文件:
open(file, 'w').write(text)
Run Code Online (Sandbox Code Playgroud)
如果脚本被中断,那么文件写入没有完成我想要没有文件而不是部分完整的文件.可以这样做吗?
python是否有任何内置功能?我的想法是,如果将文件输出到已存在该名称的文件的目录,它将以某种操作系统的工作方式工作.即:如果"file.pdf"存在,它将创建"file2.pdf",并且下次"file3.pdf".
我有以下代码(为简洁起见而简化):
import os
import errno
import imp
lib_dir = os.path.expanduser('~/.brian/cython_extensions')
module_name = '_cython_magic_5'
module_path = os.path.join(lib_dir, module_name + '.so')
code = 'some code'
have_module = os.path.isfile(module_path)
if not have_module:
pyx_file = os.path.join(lib_dir, module_name + '.pyx')
# THIS IS WHERE EACH PROCESS TRIES TO WRITE TO THE FILE. THE CODE HERE
# PREVENTS A RACE CONDITION.
try:
fd = os.open(pyx_file, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
except OSError as e:
if e.errno == errno.EEXIST:
pass
else:
raise
else:
os.fdopen(fd, 'w').write(code)
# THIS …Run Code Online (Sandbox Code Playgroud)