Skip to content

Instantly share code, notes, and snippets.

@swinton
Created March 27, 2012 10:46
Show Gist options
  • Select an option

  • Save swinton/2214778 to your computer and use it in GitHub Desktop.

Select an option

Save swinton/2214778 to your computer and use it in GitHub Desktop.
Joins a bunch of CSVs, sends the single joined CSV to STDOUT
#!/usr/bin/env python
"""
Joins a bunch of CSVs, sends the single joined CSV to STDOUT
"""
import codecs, csv, sys
try:
import cStringIO as StringIO
except ImportError:
import StringIO
class UTF8Recoder:
"""
Iterator that reads an encoded stream and reencodes the input to UTF-8
"""
def __init__(self, f, encoding):
self.reader = codecs.getreader(encoding)(f)
def __iter__(self):
return self
def next(self):
return self.reader.next().encode("utf-8")
class UnicodeCSVReader:
"""
A CSV reader which will iterate over lines in the CSV file "f",
which is encoded in the given encoding.
"""
def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
f = UTF8Recoder(f, encoding)
self.reader = csv.reader(f, dialect=dialect, **kwds)
def next(self):
row = self.reader.next()
return [unicode(s, "utf-8") for s in row]
def __iter__(self):
return self
class UnicodeCSVWriter:
"""
A CSV writer which will write rows to CSV file "f",
which is encoded in the given encoding.
Adapted from http://docs.python.org/library/csv.html#examples
"""
def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
# Redirect output to a queue
self.queue = StringIO.StringIO()
self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
self.stream = f
self.encoder = codecs.getincrementalencoder(encoding)()
def writerow(self, row):
self.writer.writerow([s.encode("utf-8") if hasattr(s, "encode") else s for s in row])
# Fetch UTF-8 output from the queue ...
data = self.queue.getvalue()
data = data.decode("utf-8")
# ... and reencode it into the target encoding
data = self.encoder.encode(data)
# write to the target stream
self.stream.write(data)
# empty queue
self.queue.truncate(0)
def writerows(self, rows):
for row in rows:
self.writerow(row)
def join_csv(*files):
headers_written = False
writer = UnicodeCSVWriter(sys.stdout)
for file in files:
reader = UnicodeCSVReader(open(file))
headers = reader.next()
if not headers_written:
writer.writerow(headers)
headers_written = True
writer.writerows(reader)
if __name__ == "__main__":
join_csv(*sys.argv[1:])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment