Skip to content

Instantly share code, notes, and snippets.

@dermoth
Created February 26, 2015 11:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dermoth/76be0bc58b5e9ba5e85e to your computer and use it in GitHub Desktop.
Save dermoth/76be0bc58b5e9ba5e85e to your computer and use it in GitHub Desktop.
Convert CSV to TSV, properly handling intra-field commas, newlines and quoted double-quotes, as per rfc4180 section 2. Also convert TSV separators to C-style escapes.
#!/usr/bin/env python
#
# Convert CSV to TSV, properly handling intra-field commas, newlines and
# quoted double-quotes, as per rfc4180 section 2. Also convert TSV separators
# to C-style escapes.
#
from __future__ import print_function
import sys, csv
with sys.stdin as f:
reader = csv.reader(f, strict=True)
for row in reader:
for col in row:
# Replace TSV delimiters with C-style escapes.
col = col.replace('\n', '\\n')
col = col.replace('\t', '\\t')
print(col, end='\t')
print()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment