0

In the code below, I need to print out the first 5 lines from the CSV file "winners.csv" and I don't know how to do it. I just know that lines 4-5 will cause all lines in the csv file to print.

The code in question:

wins = open("winners.csv", "r")
csv1 = csv.reader(wins, delimiter=",")
sort = sorted(csv1,key=operator.itemgetter(1),reverse=True)
for eachline in sort:
    print(eachline)
wins.close()
martineau
  • 119,623
  • 25
  • 170
  • 301
Alex
  • 43
  • 4
  • 1
    Your question is misleading. You don't need the first 5 lines of a file. `sorted()` always returns a list, so you simply need the first 5 elements of a list... – Tomerikoo Nov 10 '20 at 16:41
  • @Tomerikoo: It was linked to wrong duplicate — and can be closed again if it is a dup of some other one. – martineau Nov 10 '20 at 16:55

3 Answers3

1

Instead of looping through all elements in sort, loop through first five.

wins = open("winners.csv", "r")
csv1 = csv.reader(wins, delimiter=",")
sort = sorted(csv1,key=operator.itemgetter(1),reverse=True)
for eachline in sort[:5]: # <----- note how sort is changed to sort[:5]
    print(eachline)
wins.close()

Not directly related to your question, just mentioning a good practice. It's recommended to open files using with. Exception handling, closing the file after reading is done etc. will be done for you and your code will be cleaner.

with open("winners.csv", "r") as wins:
    csv1 = csv.reader(wins, delimiter=",")
    sort = sorted(csv1,key=operator.itemgetter(1),reverse=True)
    for eachline in sort[:5]:
        print(eachline)
Raiyan
  • 1,589
  • 1
  • 14
  • 28
0

The enumerate function allows you get the value and index of an iterator.

So you can check how many lines you've printed and break out of the loop:

with open('winners.csv', 'r') as f:
    for index, line in enumerate(f):
        print(line)
        if index >= 5:
            break
Paul H
  • 65,268
  • 20
  • 159
  • 136
0

Here you can use slicing and with (to ensure the file stream has closed):

import csv,operator
with open("winners.csv", "r") as wins:
  csv1 = csv.reader(wins, delimiter=",")
  sort = sorted(csv1,key=operator.itemgetter(1),reverse=True)
  for eachline in sort[:5]: 
    print(eachline)

Easiest with pandas:

import pandas as pd
df = pd.read_csv('winners.csv').head(5)
Wasif
  • 14,755
  • 3
  • 14
  • 34