Created
January 13, 2011 19:59
-
-
Save JeffSackmann/778481 to your computer and use it in GitHub Desktop.
turn a .csv file into a 2-dimensional python matrix (an array of arrays)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# turn a .csv file into a 2-dimensional python matrix (a list of lists) | |
# this will not make you happy if cells have commas in them, however escaped they may be | |
# reverse the process (go from matrix to .csv) with gist: 778484 | |
def fixText(text): | |
row = [] | |
z = text.find(',') | |
if z == 0: row.append('') | |
else: row.append(text[:z]) | |
for x in range(len(text)): | |
if text[x] != ',': pass | |
else: | |
if x == (len(text)-1): row.append('') | |
else: | |
if ',' in text[(x+1):]: | |
y = text.find(',', (x+1)) | |
c = text[(x+1):y] | |
else: c = text[(x+1):] | |
row.append(c) | |
return row | |
def createTuple(oldFile): | |
## oldFile is filename (e.g. 'sheet.csv') | |
f1 = open(oldFile, "r") | |
tup = [] | |
while 1: | |
text = f1.readline() | |
if text == "": break | |
else: pass | |
if text[-1] == '\n': | |
text = text[:-1] | |
else: pass | |
row = fixText(text) | |
tup.append(row) | |
return tup |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment