Dan Pollard
Dan Pollard

Reputation: 51

Python CSV file is not being read as expected

I have a piece of code that is supposed to extract data from a csv file, which is made up of two columns of numbers. The code looks like

from csv import reader

CMdata = reader(open('CMdata.csv', 'rU'))

BrSquared = []
for column in CMdata:
    BrSquared.append(column[0])

print BrSquared

This is producing a list. I expected it to read the first column and print the values, which would be

['2000, 2000, 3000,...,4950], 

but it reads the whole file, producing a list like

['2000\t\t0.00000002068', '2000\t\t0.00000002068',..., '4950\t\t0.00000004754'].

Why is this? How can I produce a list like the one I want?

Upvotes: 0

Views: 106

Answers (2)

joydeep bhattacharjee
joydeep bhattacharjee

Reputation: 1319

Seems like your file has some tab delimited data as well as the column that you want to parse is the first column. Please check if the following code helps you.

CMdata = reader(open('CMdata.csv', 'rU'))
[x[0].split("\t")[0] for x in CMdata]

Upvotes: 0

Alexander Ejbekov
Alexander Ejbekov

Reputation: 5960

Seems like your csv is using a \t as a separator

try:

CMdata = reader(open('CMdata.csv', 'rU'), delimiter="\t")

Upvotes: 2

Related Questions