0

I am learing comprehension and i can't figure out how to run a for loop a N amount of times. In this case I want to import the first 5 lines of a .csv file. But I want to understand the logic for further solutions.

    def columnMatch(self):
    with open(self.file_path) as csvfile:
        readcsv = csv.reader(csvfile, delimiter=';')
        line_count = 0
        row_list = []
        for row in readcsv:
            if line_count < 5:
                row_list.append(row)
                line_count += 1
    return row_list
Roy
  • 3
  • 1
  • 3
  • As your code is currently, you want to `break` the loop once the criteria is exceeded. – roganjosh Sep 15 '18 at 11:28
  • 1
    Also, there is no list comprehension in your code – roganjosh Sep 15 '18 at 11:30
  • `from itertools import islice` and `for row in islice(readcsv, 5):` limits the loop to 5 iterations. – Martijn Pieters Sep 15 '18 at 11:36
  • Thank you @MartijnPieters. I figured it out thanks to your comment: row_list = [row for row in islice(readcsv,5)] does the trick. – Roy Sep 15 '18 at 11:44
  • @Roy: so would `row_list = list(islice(readcsv, 5))`; no need to use a list comprehension when all the list comprehension does is echo the loop target. :-) (`row` is the loop target in your loop). – Martijn Pieters Sep 15 '18 at 12:57

1 Answers1

-1

You can use enumerate function to do it easier like:-

...
readcsv = csv.reader(csvfile, delimiter=';')
row_list = []
for i, row in enumerate(readcsv):
    if i < 5:
        row_list.append(row)
    else:
        break
...
Azhy
  • 704
  • 3
  • 16