John
John

Reputation: 167

Splitting a row from csv into lines in python

I have a comma seperated csv file and I want to output all the values from the first row only, with a "count" number prefixed to the values I'm outputting. My output should look like this:

0 row1col1
1 row1col2
2 row1col3
...
n row1coln

I can't see how to split the reader object, as split does not work on it.

So far I have:

import csv
reader_object = csv.reader(open('Film.csv'))

for i in range(1):
    print i,reader_object.next()

which gives me

0 ['value1', 'value2', 'value3']

Upvotes: 1

Views: 3421

Answers (3)

crennie
crennie

Reputation: 674

You can iterate over the values in the first row like this:

import csv
reader_object = csv.reader(open('Film.csv'))

for index, col_value in enumerate(reader_object.next()):
    print '{} {}'.format(index, col_value)

outputs:

0 'value1'
1 'value2'
2 'value3'
etc.

The Reader object returned by csv.reader() wraps the iterator you give it (in this case, a file handle), and provides a next() method which returns successive lines; before returning them, it turns each line into a list by splitting on a delimiter from the Dialect provided, using a comma as the default if none was given.

With this list of column values from the first row, we can iterate with a for loop and use enumerate() to give us an incrementing index as it iterates.

Upvotes: 0

dawg
dawg

Reputation: 104092

Try using enumerate:

reader_object = csv.reader(open('Film.csv'))

for i, line in enumerate(reader_object):
    print i,line

If you have a csv like so:

c1 c2 c3
cc1 cc2 cc3
ccc1 ccc2 ccc3

If you want to join together into a column you can do:

with open('Film.csv') as f:
    reader_object = csv.reader(f, delimiter=' ')
    i=0
    for line in reader_object:
        for x in line:
            print i, ''.join(x)
            i+=1   

Prints:

0 c1
1 c2
2 c3
3 cc1
4 cc2
5 cc3
6 ccc1
7 ccc2
8 ccc3

Upvotes: 1

Vijay Kumar
Vijay Kumar

Reputation: 345

You should use like this below example

import csv
i = 0
with open('Film.csv', 'rb') as csvfile:
    file_reader = csv.reader(csvfile)
    for row in file_reader:
        for col in row:
            print i, col.strip()
            i += 1

Upvotes: 0

Related Questions