- Back to Home »
- Python- Read from csv file without csv package
Posted by : ANIL KUMAR MULA
Monday, 17 November 2014
The following function is used to read an excel(csv) and return a dictionary which contains all the lines of the csv file
#the function takes a csv file as input and returns a dictionary
def read_annual(file_name,report):
# The function is defined to read data from the csv file
try: # to handle exception while opening file
f = open(file_name, 'r') #to open the file
except:
return "File Not Fount"
for line in f: # to read line by line from the csv file
mod_line = line.replace('","',';') #to replace "," by ;
mod_line = mod_line.replace(',','') #to remove 1000 seperator
mod_line = mod_line.replace(mod_line[0],'') #to remove the first and last double quote
mod_line = mod_line.replace(mod_line[0],'') #to remove the dot
line_list=mod_line.split(";") # to split the line into strings(words) based on ;
key=line_list[0] # key for dictionary
value = line_list[3].replace('\n','') #to replace new line by empty char
report.setdefault(key, []).append(value)
#report.append(value) #to push data into the report dictionary
f.close()
return report
