Skip to content

Instantly share code, notes, and snippets.

@jmsdnns
Last active February 29, 2016 04:01
Show Gist options
  • Save jmsdnns/c3df928ce49f97a3c848 to your computer and use it in GitHub Desktop.
Save jmsdnns/c3df928ce49f97a3c848 to your computer and use it in GitHub Desktop.
From CSV sheets to InDesign
#!/usr/bin/env python
# Copy this code into a file called meeseeks.py
# Run like: $ python meeseeks.py file_1.csv file_2.csv file_3.csv
# Output is a new csv called meeseeks.csv
import csv
import sys
import os
# Get files list
files = sys.argv[1:]
# Check if all files listed actually exist and error if any dont
not_files = filter(lambda f: not os.path.isfile(f), files)
if len(not_files) > 0:
wat = ', '.join(not_files)
error_msg = "I'm a stickler meeseeks. These files don't exist: %s" % wat
sys.exit(error_msg)
# Each file is represented as an item in files data.
# Each row in the file is accumulated as a flat list
files_data = []
# The header data is a list of cell labels and is computed from first file
header_data = []
# We accumulate row labels only from first file
row_label = 'a'
for file_counter, f in enumerate(files):
file_data = []
with open(f, 'rb') as csvfile:
csvreader = csv.reader(csvfile)
cols = len(csvreader.next()) # consume header line while counting columns
for row in csvreader:
# create header line from first file as row label+column number for
# each item
if file_counter == 1:
header_data = header_data + [row_label + str(i) for i in xrange(cols)]
row_label = chr(ord(row_label) + 1) # increment label
# every row in input csv is put on a single line in output
file_data = file_data + row
# every input file is a single line of output csv
files_data.append(file_data)
# write output to meeseeks.csv
with open('meeseeks.csv', 'wb') as csvfile:
output = csv.writer(csvfile)
output.writerow(header_data)
for row in files_data:
output.writerow(row)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment