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 
5
  • As your code is currently, you want to break the loop once the criteria is exceeded. Commented Sep 15, 2018 at 11:28
  • 1
    Also, there is no list comprehension in your code Commented Sep 15, 2018 at 11:30
  • from itertools import islice and for row in islice(readcsv, 5): limits the loop to 5 iterations. Commented Sep 15, 2018 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. Commented Sep 15, 2018 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). Commented Sep 15, 2018 at 12:57

1 Answer 1

-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 ... 
Sign up to request clarification or add additional context in comments.

1 Comment

This would iterate over the remainder of the file without any need to do so.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.