繁体   English   中英

读取文件后打印随机行数

[英]Print random number of lines after read a file

我正在编写一个启用线程的python程序,该程序可以读取文件并发送,但是有什么方法可以让该程序一次读取和发送N行?

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

以下python代码只能让我一次发送一行,然后倒带。

如果遵循代码逻辑,则在for循环中遍历文件中的各行,将文件指针在打印后立即重置为第一行。 这就是为什么您打印相同的第一行的原因。 要获得随机数量的印刷行,您可以采用多种方法来实现,例如:

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

在那里,在将文件内容读入各lines ,代码将在每行上循环,但仅直到通过randint(1, len(lines))计算出的第n个索引,并至少避免0 randint(1, len(lines))打印一行。 打印循环后,我们重置文件指针,然后进入睡眠状态。

修订:给定了新的细节,我们现在在每个周期将要打印的线窗口随机化,同时沿已打印的线移动。 基本上,每次迭代时滑动窗口的长度都是随机的,请确保(应该)与数组的大小一致。 根据需要进行调整。

这样的东西?

from random import randint
import sys
import threading
import time

def function():
    fo = open("1.txt", "r")
    print "Name of the file: ", fo.name
    lines = fo.readlines()
    while lines:
        toSend = ""
        for i in range(0,random.randint(x,y)): #plug your range in
            toSend += lines.pop(0)
        print(toSend)

game = threading.Thread(target=function)  
game.start()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM