read CSV file in Python
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:
but the output was an empty list ([]) :-(
Then I found the type of portfolio object using
If you have any better idea, please share.
To know more about csv module, http://docs.python.org/lib/module-csv.html
import csv
portfolio = csv.reader(open("portfolio.csv", "rb"))
names = []
for data in portfolio:
names.append(data[0])
print names
but 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 names
If you have any better idea, please share.
To know more about csv module, http://docs.python.org/lib/module-csv.html
Comments
portfolio = csv.reader(open("portfolio.csv", "rU"))
It should work
Thank you,
Suprabhath
tejsupra@gmail.com
this list can then be ordered in antoher part of the program.
Mind that these are my very first lines of code ever, so sorry probably i missed some good coding conventions and such, anyway the code looks like this:
def csvimport(filename='book2.csv'):
#import cvslist containing bids of all players and convert it to a list of tuples, namely the bidlist
import csv
#open filename
filename='book2.csv'
bidfile=csv.reader(open(filename,"rU"),dialect='excel',delimiter=";")
bidlist = []
for row in bidfile:
#Append row as tuble to larger bidlist
for i in range(len(row)):
#convert strings in file to tuple of floats and/or intigers
try:
t=int(row[i])
row[i]=t
except ValueError:
t=float(row[i])
row[i]=t
row=tuple(row)
bidlist.append(row)
return bidlist
list = [ x[0] for x in cvs.reader(open('x.csv'),'r') ]
but the parenthesis is in the wrong spot:
list = [ x[0] for x in cvs.reader(open('x.csv','r')) ]
import csv
list = [ x[0] for x in csv.reader(open('x.csv','r')) ]
list = list(portfolio)
In a one-liner:
portfolio = list(csv.reader(open("portfolio.csv", "r")))
def __init__(self, fileName):
#instantiate the CSV file variable:
self.fileName = fileName
#read the CSV file and open it:
self.fileReader = csv.reader(open(self.fileName, "rb"), delimiter = ',')
#create a local array to hold the CSV data:
self.fileReaderList = []
#pop the file data into the local array:
for data in self.fileReader:
self.fileReaderList.append(data)
The only problem with your code was you put data[0], which will only give you the first element of the array. Using data, you get the full list.
For more info and direct codes use this link this will helps you.
http://articlesdictionary.wordpress.com/2013/09/29/read-csv-file-in-python/