Python: Using itertools to get previous, current, and next item in list from text file
Question: I have setup my code as outlined in [this
answer](http://stackoverflow.com/a/1012089/571600) (shown below):

    
    
    from itertools import tee, islice, chain, izip
    
    def previous_and_next(some_iterable):
        prevs, items, nexts = tee(some_iterable, 3)
        prevs = chain([None], prevs)
        nexts = chain(islice(nexts, 1, None), [None])
        return izip(prevs, items, nexts)
    
    x = open('out2.txt','r')
    lines = x.readlines()
    
    for previous, item, next in previous_and_next(lines):
        print "Current: ", item , "Next: ", next, "Previous: ", previous
        if item == '0':
            print "root"
        elif item == '2':
            print "doc"
        else:
            print "none"
    
    x.close()
    

`out2.txt` looks like this:

    
    
    0
    2
    4
    6
    8
    10
    

This code works fine when using something like `list = [0,2,4,6,8,10]` but not
when using the lines of a text file into a list. How can I use the lines of a
text file as a list. Isn't `x.readlines()` doing this? Ultimately I need to be
able to print output depending on the `item, next, and previous` results.

Current output is:

    
    
    Current:  0
    Next:  2
    Previous:  None
    none
    Current:  2
    Next:  4
    Previous:  0
    
    none
    Current:  4
    Next:  6
    Previous:  2
    
    none
    Current:  6
    Next:  8
    Previous:  4
    
    none
    Current:  8
    Next:  10 Previous:  6
    
    none
    Current:  10 Next:  None Previous:  8
    
    none
    

Desired output should be:

    
    
    Current:  0
    Next:  2
    Previous:  None
    **root**
    
    Current:  2
    Next:  4
    Previous:  0
    **doc**
    
    none
    Current:  4
    Next:  6
    Previous:  2
    
    none
    Current:  6
    Next:  8
    Previous:  4
    
    none
    Current:  8
    Next:  10 Previous:  6
    
    none
    Current:  10 Next:  None Previous:  8
    
    none
    


Answer: The `readlines()` method of a file object returns a list of the lines of the
file _including the newline characters_. Your checks compare with strings not
including newline characters, so they always fail.

One way of getting rid of the newline characters is

    
    
    lines = (line.strip() for line in open("out2.txt"))
    

(Note that you don't need `readlines()` \-- you can directly iterate over the
file object itself.)

