Package tlib :: Package base :: Module CsvHelper
[hide private]
[frames] | no frames]

Source Code for Module tlib.base.CsvHelper

 1  import os 
 2  import csv 
 3  from ExceptionHelper import FileNotExistError 
 4  from StringIO import StringIO 
 5   
 6   
7 -def csv2dict(input_file):
8 """ 9 Convert csv data to dictionary, the result will be stored in data attribute 10 11 @param input_file : path to the excel file or a StringIO object 12 @type input_file: str | StringIO 13 @return: list[dict] 14 @raise FileNotExistError: File does not exist 15 @raise TypeError: File parameter is not of type str or StringIO 16 """ 17 data = [] 18 19 if type(input_file) is str: 20 # input_file is a path 21 if not os.access(input_file, os.F_OK): 22 raise FileNotExistError('Cannot find the csv file [%s]' % input_file) 23 24 with open(input_file, 'rb') as f: 25 rows = csv.DictReader(f) 26 for row in rows: 27 data.append(row) 28 29 return data 30 31 elif isinstance(input_file, StringIO): 32 # input_file is a StringIO object 33 rows = csv.DictReader(input_file) 34 for row in rows: 35 data.append(row) 36 37 return data 38 39 else: 40 raise TypeError('input_file argument but be of type str or StringIO')
41