blog.humaneguitarist.org

just goofin' with a little Python CSV function and a limerickesque

[Fri, 17 Feb 2012 01:44:12 +0000]
This is probably a total waste of anyone's time but ... The other night, after I'd worked on the Aguado Rondo (Op. 2, #2 [http://www.muslib.se/ebibliotek/boije/pdf/Boije%202.pdf]), I started goofing around with a little Python function that would turn a delimited text file into a Python dictionary, allowing me to target a specific cell in a delimited file, i.e. a "spreadsheet", without using the CSV module. It works (well, at least I hope it does) this way: films = csv2dict("films.txt", ";") #pass filename and delimiter print films["title"] #print "title" column sans the header print films["title"][-1] #prints last cell in the "title" column It seems helpful to be able to do this. I've tested it with a UTF-8 file to write to file with some accent markings on people's names, etc. but I'm pretty sure it'll break on stuff I haven't thought of. Anyway, maybe it'll come in handy to me for something. Here's the function: def csv2dict(fileName, delimiter): f = open(fileName, "r") #open file lines = f.read() #read file f.close() #close file rows = lines.split("\n") #put lines in list headers = rows[0].split(delimiter) #put header titles in list rows.pop(0) #remove header from "rows" list i = 0 worksheet = {} for header in headers: #for each header, i.e. each column columnCells = [] for row in rows: #for each non-header row in delimited file if row != "": rowCells = row.split(delimiter) #get cells in row columnCells.append(rowCells[i]) #put column's cells in list worksheet[header] = columnCells #set header as KEY and set "columnCells" list as VALUE i = i + 1 return worksheet And for any guitarists out there, here's a little silly rhyme I wrote when living in my home eternal, Charleston, SC. I know the Sor as "warrior against the French" thing isn't accurate, but it helps the punchline. :P The title is, of course, that as Sor's famous duet [http://www.tecla.com/extras/1001/1200/1208notes.htm]. <em>"Le Deux Ami</em>" Fernando Sor, who served in the war, fought Bonaparte in the army. But Dionisio Aguado, who lacked such bravado, preferred to run home to his mommy.