merge_csv.py 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. #!/usr/bin/env python
  2. #
  3. # Copyright (C) 2018 The Android Open Source Project
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. """Merge multiple CSV files, possibly with different columns.
  17. """
  18. import argparse
  19. import csv
  20. import io
  21. import heapq
  22. import itertools
  23. import operator
  24. from zipfile import ZipFile
  25. args_parser = argparse.ArgumentParser(
  26. description='Merge given CSV files into a single one.'
  27. )
  28. args_parser.add_argument(
  29. '--header',
  30. help='Comma separated field names; '
  31. 'if missing determines the header from input files.',
  32. )
  33. args_parser.add_argument(
  34. '--zip_input',
  35. help='Treat files as ZIP archives containing CSV files to merge.',
  36. action="store_true",
  37. )
  38. args_parser.add_argument(
  39. '--key_field',
  40. help='The name of the field by which the rows should be sorted. '
  41. 'Must be in the field names. '
  42. 'Will be the first field in the output. '
  43. 'All input files must be sorted by that field.',
  44. )
  45. args_parser.add_argument(
  46. '--output',
  47. help='Output file for merged CSV.',
  48. default='-',
  49. type=argparse.FileType('w'),
  50. )
  51. args_parser.add_argument('files', nargs=argparse.REMAINDER)
  52. args = args_parser.parse_args()
  53. def dict_reader(csvfile):
  54. return csv.DictReader(csvfile, delimiter=',', quotechar='|')
  55. csv_readers = []
  56. if not args.zip_input:
  57. for file in args.files:
  58. csv_readers.append(dict_reader(open(file, 'r')))
  59. else:
  60. for file in args.files:
  61. with ZipFile(file) as zipfile:
  62. for entry in zipfile.namelist():
  63. if entry.endswith('.uau'):
  64. csv_readers.append(
  65. dict_reader(io.TextIOWrapper(zipfile.open(entry, 'r')))
  66. )
  67. if args.header:
  68. fieldnames = args.header.split(',')
  69. else:
  70. headers = {}
  71. # Build union of all columns from source files:
  72. for reader in csv_readers:
  73. for fieldname in reader.fieldnames:
  74. headers[fieldname] = ""
  75. fieldnames = list(headers.keys())
  76. # By default chain the csv readers together so that the resulting output is
  77. # the concatenation of the rows from each of them:
  78. all_rows = itertools.chain.from_iterable(csv_readers)
  79. if len(csv_readers) > 0:
  80. keyField = args.key_field
  81. if keyField:
  82. assert keyField in fieldnames, (
  83. "--key_field {} not found, must be one of {}\n"
  84. ).format(keyField, ",".join(fieldnames))
  85. # Make the key field the first field in the output
  86. keyFieldIndex = fieldnames.index(args.key_field)
  87. fieldnames.insert(0, fieldnames.pop(keyFieldIndex))
  88. # Create an iterable that performs a lazy merge sort on the csv readers
  89. # sorting the rows by the key field.
  90. all_rows = heapq.merge(*csv_readers, key=operator.itemgetter(keyField))
  91. # Write all rows from the input files to the output:
  92. writer = csv.DictWriter(
  93. args.output,
  94. delimiter=',',
  95. quotechar='|',
  96. quoting=csv.QUOTE_MINIMAL,
  97. dialect='unix',
  98. fieldnames=fieldnames,
  99. )
  100. writer.writeheader()
  101. # Read all the rows from the input and write them to the output in the correct
  102. # order:
  103. for row in all_rows:
  104. writer.writerow(row)