blob: 4f654e8d4819f835c15b43865fe7f5c114671b0b [file] [log] [blame]
Wei-Yu Chenad55cb82022-02-15 20:07:01 +08001# SPDX-FileCopyrightText: 2020 The Magma Authors.
2# SPDX-FileCopyrightText: 2022 Open Networking Foundation <support@opennetworking.org>
3#
4# SPDX-License-Identifier: BSD-3-Clause
Wei-Yu Chen49950b92021-11-08 19:19:18 +08005
6import codecs
7import os
8
9
10def write_to_file_atomically(filename, value, temp_filename=None):
11 """
12 Atomically write to a file by first writing the value to a temp file, then
13 moving that temp file to the specified file location.
14
15 This function will create all directories necessary for the file as well.
16
17 Args:
18 filename: full path to the file to write to
19 value: value to write to the file
20 temp_filename: requested path of the intermediate temp file
21 mode: mode to open the file
22 """
23 os.makedirs(os.path.dirname(filename), exist_ok=True)
24 temp_filename = temp_filename or '{}.tmp'.format(filename)
25 with codecs.open(temp_filename, 'w', encoding='utf8') as f:
26 f.write(value)
27 f.flush()
28 os.fsync(f.fileno())
29 os.replace(temp_filename, filename)