blob: dc13a5c6c903205940b96e68eaa0c4d4b94a3ef8 [file] [log] [blame]
Wei-Yu Chen49950b92021-11-08 19:19:18 +08001"""
2Copyright 2020 The Magma Authors.
3
4This source code is licensed under the BSD-style license found in the
5LICENSE file in the root directory of this source tree.
6
7Unless required by applicable law or agreed to in writing, software
8distributed under the License is distributed on an "AS IS" BASIS,
9WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10See the License for the specific language governing permissions and
11limitations under the License.
12"""
13
14import codecs
15import os
16
17
18def write_to_file_atomically(filename, value, temp_filename=None):
19 """
20 Atomically write to a file by first writing the value to a temp file, then
21 moving that temp file to the specified file location.
22
23 This function will create all directories necessary for the file as well.
24
25 Args:
26 filename: full path to the file to write to
27 value: value to write to the file
28 temp_filename: requested path of the intermediate temp file
29 mode: mode to open the file
30 """
31 os.makedirs(os.path.dirname(filename), exist_ok=True)
32 temp_filename = temp_filename or '{}.tmp'.format(filename)
33 with codecs.open(temp_filename, 'w', encoding='utf8') as f:
34 f.write(value)
35 f.flush()
36 os.fsync(f.fileno())
37 os.replace(temp_filename, filename)