Skip to content

Instantly share code, notes, and snippets.

@mdengler
Created June 11, 2012 03:12
Show Gist options
  • Save mdengler/2908331 to your computer and use it in GitHub Desktop.
Save mdengler/2908331 to your computer and use it in GitHub Desktop.
CSV -> vertical display
#!/usr/bin/env python
"""
Displays a CSV file's contents vertically.
Example:
$ cat | ~/bin/csvvert.py
Year,Make,Model,Length
1981,Ford,Capri Ghia,2.34
1986,Ford,Reliant Regal,2.34
1990,Ford,Sierra RS Cosworth,2.38
Year: 1981
Make: Ford
Model: Capri Ghia
Length: 2.34
Year: 1986
Make: Ford
Model: Reliant Regal
Length: 2.34
Year: 1990
Make: Ford
Model: Sierra RS Cosworth
Length: 2.38
"""
import csv
import os
import sys
lines = sys.stdin.readlines()
fields = list(csv.reader(lines[0:1]))[0]
max_fieldname_length = max([len(f) for f in fields])
lineformat = "%%%is: %%s%%s" % max_fieldname_length
csvreader = csv.DictReader(lines)
for row in csvreader:
for field in fields:
sys.stdout.write(lineformat % (field, row[field], os.linesep))
sys.stdout.write(os.linesep)
@hollobon
Copy link

wise car choices

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment