Created
July 30, 2018 14:51
-
-
Save flying-sheep/b7bd31c49a57cba9f0dba741ed2b0beb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import sys | |
import csv | |
from argparse import ArgumentParser | |
from pathlib import Path | |
from openpyxl import Workbook | |
exts = { | |
'.tsv': '\t', | |
'.csv': ',', | |
} | |
parser = ArgumentParser() | |
parser.add_argument('output', type=Path) | |
parser.add_argument('inputs', nargs='+', type=Path) | |
parser.add_argument('--delimiter', '-d', help=f'Specify if your files don’t have extensions of {set(exts)!r}.') | |
args = parser.parse_args() | |
if args.output.is_file(): | |
print(f'Output file {args.output} already exists.', file=sys.stderr) | |
sys.exit(1) | |
wb = Workbook() | |
for f, path in enumerate(args.inputs): | |
title = path.with_suffix('').name | |
if f == 0: | |
sheet = wb.active | |
sheet.title = title | |
else: | |
sheet = wb.create_sheet(title) | |
with path.open() as file: | |
delim = exts.get(path.suffix, args.delimiter) | |
if delim is None: | |
print(f'Input file {path} has no known extension and -d is not set.', file=sys.stderr) | |
sys.exit(1) | |
reader = csv.reader(file, delimiter=delim) | |
for r, row in enumerate(reader, 1): | |
for c, cell in enumerate(row, 1): | |
sheet.cell(row=r, column=c).value = cell | |
wb.save(args.output) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment