1# Copyright 2017 - The Android Open Source Project 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); 4# you may not use this file except in compliance with the License. 5# You may obtain a copy of the License at 6# 7# http://www.apache.org/licenses/LICENSE-2.0 8# 9# Unless required by applicable law or agreed to in writing, software 10# distributed under the License is distributed on an "AS IS" BASIS, 11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12# See the License for the specific language governing permissions and 13# limitations under the License. 14 15"""File-related utilities.""" 16 17import contextlib 18import os 19import tempfile 20 21 22@contextlib.contextmanager 23def UnopenedTemporaryFile(**kwargs): 24 """Creates and returns a unopened temprary file path. 25 26 This function is similar to tempfile.TemporaryFile, except that an 27 unopened file path is returend instead of a file-like object. 28 The file will be deleted when the context manager is closed. 29 30 Args: 31 **kwargs: Any keyward arguments passed to tempfile.mkstemp (e.g., dir, 32 prefix and suffix). 33 34 Returns: 35 An unopened temporary file path. 36 """ 37 fd, path = tempfile.mkstemp(**kwargs) 38 os.close(fd) 39 40 try: 41 yield path 42 finally: 43 if os.path.exists(path): 44 os.unlink(path) 45