6

Here is a sample of my csv file:

1   Ryan    Giggs   £13.50  23  Manchester  Utd
2   David   Beckham £40.00  24  Manchester  Utd
3   Michael Owen    £22.00  22  Liverpool
4   Robbie  Fowler  £21.00  23  Leeds Utd

I have written this code with the intent to print out the first row:

import csv

with open("Footballers.csv") as f:
    reader = csv.reader(f)
    for row in reader:
        print(row[1])

However this only print out the first(technically second) column like so:

Ryan
David
Micheal
Robbie

How can I make it print out the first row like so?

1 Ryan Giggs £13.50 23 Manchester Utd
martineau
  • 119,623
  • 25
  • 170
  • 301
  • @roganjosh That would print all the rows, the asker only want the first one. – Pierre Barre Dec 03 '16 at 16:48
  • @roganjosh I did the same when I first replied to the question – Pierre Barre Dec 03 '16 at 16:51
  • @roganjosh Why setup a for loop if you only need one item. That's what `next` does. Besides the `for` loop is itself calling `next` behind the scenes. – Moses Koledoye Dec 03 '16 at 16:52
  • @MosesKoledoye exactly why I suggested "or pick one of the _more_ _elegant_ solutions". I had already seen your answer and it was explained better than one I could squish in a comment. – roganjosh Dec 03 '16 at 16:54

3 Answers3

9

row[1] gives the 2nd thing in row (because it starts counting at 0). You want all of row, separated by spaces. You can replace row[1] with " ".join(row) to fix it. " " is the thing we want each item to be separated by, and row is the list we want to separate.

The full code would be

import csv

with open("Footballers.csv") as f:
    reader = csv.reader(f)
    for row in reader:
        print(" ".join(row))
Max
  • 1,325
  • 9
  • 20
7

Drop the for loop and use next if you only intend to print the first row, as the for iterates on the object and will successively supply each row:

with open("Footballers.csv") as f:
    reader = csv.reader(f)
    print(next(reader)[0]) # default separator is a comma so you only get one item in the row

The reader object is an iterator and calling next on it will provide the next item which in this case is the first row. Note that this advances the iterator and subsequent iterations on it will start from the second row.

Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
2

Use join

import csv

with open("Footballers.csv") as f:
   reader = csv.reader(f)
   for row in reader:
   print(' '.join(row) )
SeedofWInd
  • 147
  • 1
  • 4