Python has useful module named csv to deal with csv files. But recently I faced a problem reading csv files and want to share with you how I get rid of the problem. I wanted to get the data of the first column of my csv file. I tried the following code:
import csv
portfolio = csv.reader(open("portfolio.csv", "rb"))
names = []
for data in portfolio:
names.append(data[0])
print namesbut the output was an empty list ([]) :-(
Then I found the type of portfolio object using
print type(portfolio) that the type is '_csv.reader', then I changed my program to the following and got the list :-)
import csv
portfolio = csv.reader(open("portfolio.csv", "rb"))
portfolio_list = []
portfolio_list.extend(portfolio)
names = []
for data in portfolio_list:
names.append(data[0])
print namesIf you have any better idea, please share.
To know more about csv module, http://docs.python.org/lib/module-csv.html
No comments:
Post a Comment