xref: /aosp_15_r20/external/tensorflow/tensorflow/python/keras/utils/io_utils.py (revision b6fb3261f9314811a0f4371741dbb8839866f948)
1# Copyright 2018 The TensorFlow Authors. All Rights Reserved.
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# pylint: disable=g-import-not-at-top
16"""Utilities related to disk I/O."""
17
18import os
19
20
21def path_to_string(path):
22  """Convert `PathLike` objects to their string representation.
23
24  If given a non-string typed path object, converts it to its string
25  representation.
26
27  If the object passed to `path` is not among the above, then it is
28  returned unchanged. This allows e.g. passthrough of file objects
29  through this function.
30
31  Args:
32    path: `PathLike` object that represents a path
33
34  Returns:
35    A string representation of the path argument, if Python support exists.
36  """
37  if isinstance(path, os.PathLike):
38    return os.fspath(path)
39  return path
40
41
42def ask_to_proceed_with_overwrite(filepath):
43  """Produces a prompt asking about overwriting a file.
44
45  Args:
46      filepath: the path to the file to be overwritten.
47
48  Returns:
49      True if we can proceed with overwrite, False otherwise.
50  """
51  overwrite = input('[WARNING] %s already exists - overwrite? '
52                    '[y/n]' % (filepath)).strip().lower()
53  while overwrite not in ('y', 'n'):
54    overwrite = input('Enter "y" (overwrite) or "n" '
55                      '(cancel).').strip().lower()
56  if overwrite == 'n':
57    return False
58  print('[TIP] Next time specify overwrite=True!')
59  return True
60