1

I have a csv file that contains the following values

"Spam2,pank",Spam3,Spam6,Spam7
Spam1,Spam5,Spam0,Spam9

And i am using the following python code to read a particular column

for line in open('D:\eggs2.csv','rb'):
    columns = line.split(",")
    print columns[0]

The output it gives is:-

"Spam2
Spam1

while i am expecting :

Spam2,pank
Spam1

Please Help me out on this.

2

3 Answers 3

7

You don't have to reinvent the wheel, the python csv module does a perfect job.

import csv

csv_file = open('D:\eggs2.csv','rb')
csv_reader = csv.reader(csv_file)
for row in csv_reader:
    print row[0]

csv_file.close()

@see python csv

Sign up to request clarification or add additional context in comments.

Comments

0

It depends on what data structure you want to red the csv into. This will load the data into a list of tuples. Each line will be an entry in the list and each line will be a tuple of string values.

I'd create a helper function for reading files I use this all the time

def readfile(filepath, delim):     
   with open(filepath, 'r') as f:         
      return [tuple(line.split(delim)) for line in f] 

data = readfile('D:\eggs2.csv', ',')

There are beneftis of using with (it handles the closing, excpetions e.t.c) but you'll need to be on Python 2.7+

If you want to use a '|' delimeter or somthing else in the future you don't have to re-write your code.

Comments

-1

You could split it twice. First, split it to get something like '''"\w"''', ie all alphanumberic characters inside quotes. The result is a list for each split. Then you would split again, this time for ',', for each list that resulted in your first split. Then you flatten the lists.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.