Ask Ubuntu is a question and answer site for Ubuntu users and developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have some csv files with too many columns for LibreOffice Calc to open, but only a few rows. If I can transpose the csv file, it should be ok as Calc can deal with very many more rows than columns.

share|improve this question
I doubt in what way does this really relate to Ubuntu. Just an honest doubt – Mahesh Aug 25 '12 at 7:50
up vote 4 down vote accepted

A simple python program would do the job (and since this is not really tested: backup you csv file in advance!):

import csv
import sys
infile = sys.argv[1]
outfile = sys.argv[2]

with open(infile) as f:
    reader = csv.reader(f)
    cols = []
    for row in reader:

with open(outfile, 'wb') as f:
    writer = csv.writer(f)
    for i in range(len(max(cols, key=len))):
        writer.writerow([(c[i] if i<len(c) else '') for c in cols])

You can save this into a file "" and call it from the commandline like this:

python <theinfilename> <theoutfilename>
share|improve this answer
nice, worked a treat, thanks (: I used xrange rather than range to run a bit faster (minor point!). – drevicko Nov 3 '11 at 6:06
nice script! there is extra ')' at the end, otherwise awesome. – gare Aug 24 '12 at 13:37

You can use this script from the shell like this:

$ ./transpose_csv < theinfilename > theoutfilename

And here is the script:

#!/usr/bin/env python
import sys, csv, itertools
rows = itertools.izip(*csv.reader(sys.stdin, delimiter=','))
sys.stdout.writelines(','.join(row) + '\n' for row in rows)
share|improve this answer
see also – Janus Troelsen Mar 23 '14 at 22:42
for python3 with stdin/stdout i/o: python3 -c "import sys,csv; csv.writer(sys.stdout).writerows(zip(*csv.reader(sys.stdin)))" – Janus Troelsen Mar 23 '14 at 22:45

For reference's sake, here is the same incantation in Ruby:

require 'CSV'

rows =$stdin).read
puts { |x| x.join ',' }
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.