No Comments →
Python already has a great csv module, but since it is implemented in C, it’s not available to IronPython. IronPython.info has a suggested workaround using an external library. But for some reason I just chose to write something really simple myself. Since for my purposes today I didn’t actually need to do any writing to file, I just have a csv reader.
This is my really simple csv reader. I’m calling it, icsv.py. There’s a million things it doesn’t handle yet, but it covered what I happened to need today. Maybe I’ll expand it as the situation warrants.
class reader: def __init__(self,path,delimiter=','): self.File = open(path, "r") self.Delimiter = delimiter self.Header = self.File.readline().replace('\n','').split(delimiter) self.__curr_line = None def canread(self): return not self.File.closed def stop(self): self.File.close() def nextline(self): if self.File.closed: return None curr = self.File.readline() if not curr: self.File.close() return None self.__curr_line = curr ## no quoted text return the easy way... if curr.find('"') == -1: return dict(zip(self.Header,self.__curr_line.replace('\n','').split(self.Delimiter))) line = dict() for h in self.Header: if not curr.startswith('"'): line[h], s, curr = curr.partition(',') else: clsq = curr.find('"',1)+1 line[h] = curr[0:clsq] curr = curr[clsq+1:] return lineTags: IronPython, read csv file