Wei-Yu Chen | ad55cb8 | 2022-02-15 20:07:01 +0800 | [diff] [blame] | 1 | # 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 Chen | 49950b9 | 2021-11-08 19:19:18 +0800 | [diff] [blame] | 5 | |
| 6 | import codecs |
| 7 | import os |
| 8 | |
| 9 | |
| 10 | def 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) |