blob: 5ad61b2f69928091bc9d090ee1da686589c8b7e5 [file] [log] [blame]
Paul Duffinfdada682021-02-08 18:08:09 +00001#!/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"""
17Merge multiple CSV files, possibly with different columns.
18"""
19
20import argparse
21import csv
22import io
23
24from zipfile import ZipFile
25
26args_parser = argparse.ArgumentParser(description='Merge given CSV files into a single one.')
27args_parser.add_argument('--header', help='Comma separated field names; '
28 'if missing determines the header from input files.')
Paul Duffin031d8692021-02-12 11:46:42 +000029args_parser.add_argument('--zip_input', help='Treat files as ZIP archives containing CSV files to merge.',
30 action="store_true")
Paul Duffinfdada682021-02-08 18:08:09 +000031args_parser.add_argument('--output', help='Output file for merged CSV.',
32 default='-', type=argparse.FileType('w'))
33args_parser.add_argument('files', nargs=argparse.REMAINDER)
34args = args_parser.parse_args()
35
36
37def dict_reader(input):
38 return csv.DictReader(input, delimiter=',', quotechar='|')
39
Paul Duffinfdada682021-02-08 18:08:09 +000040csv_readers = []
Paul Duffin031d8692021-02-12 11:46:42 +000041if not(args.zip_input):
Paul Duffinfdada682021-02-08 18:08:09 +000042 for file in args.files:
43 csv_readers.append(dict_reader(open(file, 'r')))
Paul Duffin031d8692021-02-12 11:46:42 +000044else:
45 for file in args.files:
46 with ZipFile(file) as zip:
47 for entry in zip.namelist():
48 if entry.endswith('.uau'):
49 csv_readers.append(dict_reader(io.TextIOWrapper(zip.open(entry, 'r'))))
Paul Duffinfdada682021-02-08 18:08:09 +000050
51headers = set()
52if args.header:
53 fieldnames = args.header.split(',')
54else:
55 # Build union of all columns from source files:
56 for reader in csv_readers:
57 headers = headers.union(reader.fieldnames)
58 fieldnames = sorted(headers)
59
60# Concatenate all files to output:
61writer = csv.DictWriter(args.output, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL,
62 dialect='unix', fieldnames=fieldnames)
63writer.writeheader()
64for reader in csv_readers:
65 for row in reader:
66 writer.writerow(row)