Wei-Yu Chen | 49950b9 | 2021-11-08 19:19:18 +0800 | [diff] [blame^] | 1 | """ |
| 2 | Copyright 2020 The Magma Authors. |
| 3 | |
| 4 | This source code is licensed under the BSD-style license found in the |
| 5 | LICENSE file in the root directory of this source tree. |
| 6 | |
| 7 | Unless required by applicable law or agreed to in writing, software |
| 8 | distributed under the License is distributed on an "AS IS" BASIS, |
| 9 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 10 | See the License for the specific language governing permissions and |
| 11 | limitations under the License. |
| 12 | """ |
| 13 | |
| 14 | import codecs |
| 15 | import os |
| 16 | |
| 17 | |
| 18 | def 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) |