Last element in python iterator

I want to iterate over the lines of a file and print some output for each of them. All printed lines should have ,\n at the end, except for the last line.

My first approach was to use a search for the hasNext() method, which does not exist. I know that a StopIteration exception is StopIteration , but I'm not sure how I can use it, on Pythonic, to achieve what I want.

0
source share
4 answers

Here is a wrapper class for an iterator that gives you a hasNext property:

 class IteratorEx(object): def __init__(self, it): self.it = iter(it) self.sentinel = object() self.nextItem = next(self.it, self.sentinel) self.hasNext = self.nextItem is not self.sentinel def next(self): ret, self.nextItem = self.nextItem, next(self.it, self.sentinel) self.hasNext = self.nextItem is not self.sentinel return ret def __iter__(self): while self.hasNext: yield self.next() 

Demo:

 iterex = IteratorEx(xrange(10)) for i in iterex: print i, iterex.hasNext 

Print

 0 True 1 True 2 True 3 True 4 True 5 True 6 True 7 True 8 True 9 False 
+2
source

Print the first line yourself, and then the other lines added by ",\n" .

 firstline = next(thefile) print get_some_output(firstline) for line in thefile: print ",\n" + get_some_output(line) 
+6
source

Presumably you want to delete existing newlines first. Then you can iterate over the selected lines, get your result and combine the results together with ", \ n", for example:

 f = open('YOUR_FILE', 'r') print ",\n".join([get_some_output(line.rstrip("\n")) for line in f]) 
+1
source

Answers related to your question appear in several posts listed below. Although some of these questions vary significantly in the meaning of this question, most of them have such informative answers that I have listed here in any case. Note that Paul’s answer is a cleaner solution to the current problem than the following, but some of the older answers apply more generally.

β€’ Python: Quoting through everything except the last element of the list ,
β€’ Notify csv.reader when it is on the last line ,
β€’ Getting the first and last element in python for the loop ,
What is the pythonic way to detect the last element in a python for for loop? β€’ Python How to check if the last element in the tool chain of an iterator has reached ,
β€’ The cleanest way to get the last element from a python iterator ,
β€’ How to relate to the last item in a list differently in python? ,
β€’ Python: how do I know when I'm on the last for a loop ,
β€’ Ignore the last \n when using readlines with python ,
β€’ Last Python iteration for the loop,,
β€’ Python 3.x: check if the element generator has

One of the above was listed in the "Linked" list on the right sidebar for this question, but the others were not. Some of the questions in the β€œRelated” sidebar are worth a look and could be included in the list above.

+1
source

All Articles