#NEWLINE# def replace_file( file_name , data , file_mode = 420 ) : #NEWLINE# #INDENT# 'Replaces the contents of file_name with data in a safe manner.\n\n    First write to a temp file and then rename. Since POSIX renames are\n    atomic, the file is unlikely to be corrupted by competing writes.\n\n    We create the tempfile on the same device to ensure that it can be renamed.\n    ' #NEWLINE# base_dir = os . path . dirname ( os . path . abspath ( file_name ) ) #NEWLINE# with tempfile . NamedTemporaryFile ( 'w+' , dir = base_dir , delete = False ) as tmp_file : #NEWLINE# #INDENT# tmp_file . write ( data ) #NEWLINE# #UNINDENT# os . chmod ( tmp_file . name , file_mode ) #NEWLINE# os . rename ( tmp_file . name , file_name )