我有一个 Python 中的 C++ 代码生成器,可以生成许多源文件。大多数时候,只有一个文件发生变化,但由于生成器会重新生成所有文件,所以它们都会被重建。有没有办法让 Python 不覆盖文件,或者让 cmak 使用校验和来查看需要重建的内容,而不仅仅是使用文件日期?
我在想这样的事情在 Python 中会很容易:如果我可以替换
with open('blah', 'w') as f:
用这个:
with open_but_only_overwrite_if_total_output_is_different('blah', 'w') as f:
实现该目标的好方法是什么?
最佳答案
结合Neil G的代码和思路| , Petr Viktorin , gecco , 和 joel3000 :
import contextlib
@contextlib.contextmanager
def write_on_change(filename):
with tempfile.NamedTemporaryFile(delete=False) as f:
yield f
tempname = f.name
try:
overwrite = not filecmp.cmp(tempname,filename)
except (OSError,IOError):
overwrite = True
if overwrite:
shutil.copyfile(tempname,filename)
os.unlink(tempname)
一些小的补充(希望是改进):
shutil.copyfile
只复制tempname
的内容到filename
,同时保留文件权限和文件等元数据 所有权。filecmp.cmp
检查文件的大小 如果大小不匹配,则返回False
。那可能是一个不错的 如果文件很大并且有东西附加到 结尾。它还读取并比较 bufsize = 8*1024一次字节, 而不是一次一行。bufsize
通常会大于 行,这将导致更少的读取。
关于python - 输出相同时不覆盖文件的简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8718891/