cat_files.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. #!/usr/bin/env python
  2. #===----------------------------------------------------------------------===##
  3. #
  4. # Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  5. # See https://llvm.org/LICENSE.txt for license information.
  6. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  7. #
  8. #===----------------------------------------------------------------------===##
  9. from argparse import ArgumentParser
  10. import sys
  11. def print_and_exit(msg):
  12. sys.stderr.write(msg + '\n')
  13. sys.exit(1)
  14. def main():
  15. parser = ArgumentParser(
  16. description="Concatenate two files into a single file")
  17. parser.add_argument(
  18. '-o', '--output', dest='output', required=True,
  19. help='The output file. stdout is used if not given',
  20. type=str, action='store')
  21. parser.add_argument(
  22. 'files', metavar='files', nargs='+',
  23. help='The files to concatenate')
  24. args = parser.parse_args()
  25. if len(args.files) < 2:
  26. print_and_exit('fewer than 2 inputs provided')
  27. data = ''
  28. for filename in args.files:
  29. with open(filename, 'r') as f:
  30. data += f.read()
  31. if len(data) != 0 and data[-1] != '\n':
  32. data += '\n'
  33. assert len(data) > 0 and "cannot cat empty files"
  34. with open(args.output, 'w') as f:
  35. f.write(data)
  36. if __name__ == '__main__':
  37. main()
  38. sys.exit(0)