Print random number of lines after read a file
<p>I am writing a thread-enabled python program which can read a file and send, but is there any ways to let the program read and send N numbers of line at a time?</p>

<pre><code>from random import randint
import sys
import threading
import time

def function():
    fo = open("1.txt", "r")
    print "Name of the file: ", fo.name

    while True:
        line = fo.readlines()
        for lines in line:
            print(lines)
            fo.seek(0, 0)
            time.sleep(randint(1,3))

game = threading.Thread(target=function)  
game.start()
</code></pre>

<p>The following python code only can let me send one line at a time, and then rewind. </p>

<p>If you follow your code logic, in the <code>for</code> loop iterating over the lines in the file, you reset the file pointer to the first line right after having printed it. That's why you get the same first line printed. To achieve a random number of printed lines you could do that in any number of ways, for example:</p>

<pre><code>def function():
    fo = open("1.txt", "r")
    print "Name of the file: ", fo.name
    lines = fo.readlines()    # changed the var names, lines vs. line
    start_index = 0
    while True:
        length = randint(1, len(lines)-start_index)
        for line in lines[start_index:start_index+length]:
            print(line)
        start_index += length
        time.sleep(randint(1,3))
</code></pre>

<p>In there, after reading in the file content into <code>lines</code>, the code will loop on each line, but only until the n-th index, calculated via <code>randint(1, len(lines))</code>, and avoiding <code>0</code> so at the very least you get one line printed. After the print loop, we reset the file pointer, and sleep.</p>

<p>REVISION: given the new detail, at every cycle we are now randomizing the window of lines to be printed, while moving along the already printed lines. Basically a sliding window of random length at each iteration, making sure it (should) be consistent with the size of the array. Adjust as needed.</p>

python python-2.7 python-3.x