file_utils.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. # Copyright 2018 - 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. """File-related utilities."""
  15. import os
  16. import shutil
  17. import tempfile
  18. def make_parent_dirs(file_path):
  19. """Creates parent directories for the file_path."""
  20. if os.path.exists(file_path):
  21. return
  22. parent_dir = os.path.dirname(file_path)
  23. if parent_dir and not os.path.exists(parent_dir):
  24. os.makedirs(parent_dir)
  25. def filter_out(pattern_files, input_file):
  26. """"Removes lines in input_file that match any line in pattern_files."""
  27. # Prepares patterns.
  28. patterns = []
  29. for f in pattern_files:
  30. patterns.extend(open(f).readlines())
  31. # Copy lines that are not in the pattern.
  32. tmp_output = tempfile.NamedTemporaryFile()
  33. with open(input_file, 'r') as in_file:
  34. tmp_output.writelines(line for line in in_file.readlines()
  35. if line not in patterns)
  36. tmp_output.flush()
  37. # Replaces the input_file.
  38. shutil.copyfile(tmp_output.name, input_file)