Skip to content

Instantly share code, notes, and snippets.

@strawberryjello
Last active August 29, 2015 13:56
Show Gist options
  • Save strawberryjello/9319648 to your computer and use it in GitHub Desktop.
Save strawberryjello/9319648 to your computer and use it in GitHub Desktop.
Transposes the contents of a CSV file and writes the CSV result to another file.
#! /usr/bin/env python
"""CSV transposer
Transposes the contents of a CSV file and writes the CSV result to another
file.
(see: http://en.wikipedia.org/wiki/Transpose)
Runs on Python 2.7.3
"""
import unittest
def parse_csv(csv):
rows = csv.split("\n")
# assume that columns and rows are even
num_rows = len(rows)
num_columns = rows[0].count(",") + 1
matrix = []
for i in range(num_rows):
matrix.append(rows[i].split(","))
return matrix
def transpose(matrix):
# assume that columns and rows are even
num_rows = len(matrix)
num_columns = len(matrix[0])
transposed_matrix = []
for x in range(num_rows):
for y in range(num_columns):
if (x == 0): # only once for each row
transposed_matrix.append([])
transposed_matrix[y].append(matrix[x][y])
return transposed_matrix
def matrix_to_csv(matrix):
# assume that columns and rows are even
num_rows = len(matrix)
num_columns = len(matrix[0])
csv = ""
# str.join() only accepts 1 parameter in 2.7.3
# 2.7.6 - str.join(sequence [,sep])
for x in range(num_rows):
for y in range(num_columns):
csv = csv + matrix[x][y]
if (y < num_columns - 1):
csv = csv + ","
if (x < num_rows - 1):
csv = csv + "\n"
return csv
class TransposerTests(unittest.TestCase):
def test_parse_csv(self):
csv = """1,2,3
4,5,6
7,8,9
10,11,12"""
matrix = [['1','2','3'],
['4','5','6'],
['7','8','9'],
['10','11','12']]
self.assertEquals(parse_csv(csv), matrix)
def test_transpose(self):
matrix1 = [[1,2,3],
[4,5,6],
[7,8,9],
[10,11,12]]
matrix2 = [[1,4,7,10],
[2,5,8,11],
[3,6,9,12]]
self.assertEquals(transpose(matrix1), matrix2)
def test_matrix_to_csv(self):
matrix = [['1','4','7','10'],
['2','5','8','11'],
['3','6','9','12']]
csv = """1,4,7,10
2,5,8,11
3,6,9,12"""
self.assertEquals(matrix_to_csv(matrix), csv)
if __name__ == '__main__':
# unittest exits upon completion; code after the call won't be executed
# unittest.main()
filename = raw_input("Source file: ")
orig_text = ""
with open(filename, "rb") as p:
orig_text = str.strip(p.read())
transposed_text = matrix_to_csv(transpose(parse_csv(orig_text)))
split_filename = filename.split(".")
transposed_filename = split_filename[0] + "-transposed." + split_filename[1]
with open(transposed_filename, "wb") as t:
t.write(transposed_text)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment