Search code examples
pythonwhile-loopraw-input

Why while loop is sticking at raw_input? (python)


In the following code i am trying to make a "more" command (unix) using python script by reading the file into a list and printing 10 lines at a time and then asking user do you want to print next 10 lines (Print More..). Problem is that raw_input is asking again and again input if i give 'y' or 'Y' as input and do not continue with the while loop and if i give any other input the while loop brakes. My code may not be best as am learning python.

import sys
import string
lines = open('/Users/abc/testfile.txt').readlines()
chunk = 10
start = 0

while 1:
    block = lines[start:chunk]
    for i in block:
        print i
    if raw_input('Print More..') not in ['y', 'Y']:
        break
    start = start + chunk

Output i am getting for this code is:-

--
10 lines from file

Print More..y
Print More..y
Print More..y
Print More..a

Solution

  • As @Tim Pietzcker pointed out, there's no need of updating chunk here, just use start+10 instead of chunk.

    block = lines[start:start+10]
    

    and update start using start += 10.

    Another alternative solution using itertools.islice():

     with open("data1.txt") as f:
        slc=islice(f,5)            #replace 5 by 10 in your case
        for x in slc:
            print x.strip()
        while raw_input("wanna see more : ") in("y","Y"):     
            slc=islice(f,5)        #replace 5 by 10 in your case
            for x in slc:
                print x.strip()
    

    this outputs:

    1
    2
    3
    4
    5
    wanna see more : y
    6
    7
    8
    9
    10
    wanna see more : n