1

I have setup my code as outlined in this answer (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
Community
  • 1
  • 1
serk
  • 4,329
  • 2
  • 25
  • 38
  • 3
    In which way does the code fail? "It does not work fine" is rather useless information. – Sven Marnach Jan 07 '12 at 23:11
  • Added what the output currently looks like and what I'm trying to make it look like. – serk Jan 07 '12 at 23:18
  • Note that, instead of a sequence of `if`s, you can use a dictionary to map strings (node types?) to other strings (node names?). This is even simpler if you use a [default-dictionary](http://code.activestate.com/recipes/389639-default-dictionary/), which isn't a native type in Python, but is easily implemented. – outis Jan 07 '12 at 23:28

1 Answers1

3

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.)

Sven Marnach
  • 574,206
  • 118
  • 941
  • 841