Skip to content

Instantly share code, notes, and snippets.

@lysol
Created September 7, 2010 15:16
Show Gist options
  • Save lysol/568515 to your computer and use it in GitHub Desktop.
Save lysol/568515 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import csv
import sys
def main():
if len(sys.argv) != 2:
print "Usage: %s csv_file" % sys.argv[0]
exit(1)
infile = open(sys.argv[1], 'rb')
dialect = csv.Sniffer().sniff(infile.readline())
infile.seek(0)
reader = csv.reader(infile, dialect)
# Calculate lengths.
cell_lengths = []
for lind, line in enumerate(reader):
# Set up the cell_lengths list
if lind == 0:
cell_lengths = [0] * len(line)
elif len(line) > len(cell_lengths):
while len(line) > len(cell_lengths):
cell_lengths.append(0)
for index, cell in enumerate(line):
if cell_lengths[index] < len(cell):
cell_lengths[index] = len(cell)
else:
cell_lengths.append(len(cell))
# Display the file
infile.seek(0)
for line in reader:
oline = ""
for index, cell in enumerate(line):
oline += cell.ljust(cell_lengths[index] + 1, ' ')
print oline
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment